Best way to use support function in R to stay DRY - r

While working on my first R package a noticed that when the package structure gets created in the man directory "man" there is a documentation file for each function/method in the code.
In order to stay DRY (don't repeat yourself) I used some functions as "auxiliary" functions in loops or iteration. How can I tell R that I do not want to provide any documentation for them given that they should not be called directly by the end user?!?!

Use the roxygen2 and devtools packages to document your functions and build your package.
#' Function 1 Title
#'
#' Describe what function 1
#' does in a paragraph. This function
#' will be exported for external use because
#' it includes the #export tag.
#'
#' #param parameter1 describe the first parameter
#' #param parameter2 describe the second parameter
#' #examples
#' function1(letters[1:10], 1:10)
#' #export
function1 <- function(parameter1, parameter2) {
paste(parameter1, parameter2)
}
#' Function 2 Title
#'
#' Description here. This will not
#' be added to the NAMESPACE.
#'
#' #param parameter1
function2 <- function(parameter1) {
parameter1
}
Once you have all your documentation, use the tools in the devtools package to build, document, and check your package. It will automatically update the man files and DESCRIPTION, and add / remove functions from the NAMESPACE.
document()
build()
check()
I also recommend using the rbundler package to control how you load packages.

If you do not export them via the NAMESPACE you are not expected to provide documentation.
Another (older) was is too simple create one, say, internal.Rd and define a bunch of \alias{foo}, \alias{bar}, \alias{frob} and that way codetools is happy too.

thanks #Jojoshua-ulrich and #dirk-eddelbuettel
According to "Writing R Extensions":
The man subdirectory should contain (only) documentation files for the objects in the package in R documentation (Rd) format. The documentation filenames must start with an ASCII (lower or upper case) letter or digit and have the extension .Rd (the default) or .rd. Further, the names must be valid in ‘file://’ URLs, which means9 they must be entirely ASCII and not contain ‘%’. See Writing R documentation files, for more information. Note that all user-level objects in a package should be documented; if a package pkg contains user-level objects which are for “internal” use only, it should provide a file pkg-internal.Rd which documents all such objects, and clearly states that these are not meant to be called by the user. See e.g. the sources for package grid in the R distribution for an example. Note that packages which use internal objects extensively should not export those objects from their namespace, when they do not need to be documented (see Package namespaces).
By the way, is there any convention to include comments in the code so that man grabs the function description, arguments description etc directly from the code?

Related

How to create help paper for the own package?

I have created my own package with description file and help paper for every function.
Now if I code ?mypackage::myfunction R displays help paper to myfunction. But when I code ?mypackage R displays "No documentation for ‘mypackage’ in specified packages and libraries:" :(
In case you are not using roxygen2 (but you probably should), you need to create a .Rd file with the general mandatory fields, including a \docType{package}. See section 2.1.4 of the Writing R Extensions.
Apart from the mandatory \name and \title and the pkgname-package
alias, the only requirement for the package overview page is that it
include a \docType{package} statement. All other content is optional.
We suggest that it should be a short overview, to give a reader
unfamiliar with the package enough information to get started. More
extensive documentation is better placed into a package vignette (see
Writing package vignettes) and referenced from this page, or into
individual man pages for the functions, datasets, or classes.
Assuming you are using Roxygen2 to generate your documentation, somewhere you will need something like this saved in a .R file.
#' Title
#'
#' Description
#'
#' #docType package
#' #name varbinq
NULL
This will create a help file for your package that can be accessed when you type ?varbinq
For more information see this section of Hadley Wickham's book entitled R Packages.
If you are using the roxygen2 package for documenting your package called "mypackage", the documented way to do this is to write this code in a file named "mypackage.R":
#' Generate R documentation from inline comments.
#'
#' Roxygen2 allows you to write documentation in comment blocks co-located
#' with code.
#'
#' The only function you're likely to need from \pkg{roxygen2} is
#' \code{\link{roxygenize}}. Otherwise refer to the vignettes to see
#' how to format the documentation.
"_PACKAGE"
You will then be able to retrieve your package's help page using:
??mypackage

Does roxygen2 work for R scripts in data-raw?

I am using RStudio to create a package for a piece of data analysis I'm doing. To put my raw data into the package, I'm using devtools::use_data_raw() as per this article.
I have a script load-raw-data.R that loads the raw data and assembles it into a dataframe, then calls devtools::use_data() on this dataframe to add it to the package. load-raw-data.R is in /data-raw not /R, as per the article. I've added documentation to the functions in this script via a roxygen2 skeleton, however when I build the documentation the .Rd files for these functions are not built. I presume this is because roxygen2 is only looking in /R. Is there a way to tell roxygen2 to look in /data-raw as well? Or have I misunderstood something along the way?
Update: following #phil's suggestion
#phil - thanks - I tried this for one of the functions (load_data_files) in the load-raw-data.R script (see below for the documentation added to R/data.R), but on rebuilding the package I get an error: 'load_data_files' is not an exported object from 'namespace:clahrcnwlhf'. I have included the #export tag in the documentation in R/data.R. Any thoughts on how I might resolve this?
`# This script loads the individual component files of the raw dataset
# and stitches them together, saving the result as an .RData file
#' load_data_files
#'
#' load_data_files loads in a set of Excel files as dataframes
#'
#' #param fl list of paths of the files to be loaded
#'
#' #return A list of dataframes, one for each of the file paths in fl.
#' #export
"load_data_files"`

do not show function help document in building R package by roxygen2

I am using devtools to build R package, and there are some functions that are NOT designed to be visible to end-users. However, since these functions involve calling C codes by .Call, so that I have to write #useDynLib above the function for automatic generation of .Rd files. In that way, when I build the package, even I did NOT include the #export for those functions, they nonetheless appear in the help document... Is there a way to suppress those functions even if they have been documented? Thanks!
According to Hadley's comments, use #keywords internal will make the function invisible to end-users. Details can be found here in the wiki pages of devtools.
The wiki linked in the accepted answer no longer discusses #keywords internal (as of April 2016). In case it's helpful for someone to see an example:
# multiplyBy3
#' This is an example of an internal function called \code{multiplyBy3()}
#'
#' Sometimes you want internal functions as part of an R Package built with
#' RStudio and roxygen2, but you don't want .Rd files created for them
#' or to have them be visible in the help document following the build process
#'
#' #keywords internal
#'
#' #param base_num The number to multiply by three
#'
#' #import jsonlite
#'
#' #return Returns a numeric vector
#'
multiplyBy3 <- function(base_number) {
stopifnot(is.numeric(base_number))
return(base_number * 3)
}
Key bits: do not include #export and do include #keywords internal
For me, #keywords internal did not work (roxygen2 6.1.1). I was able to achieve the desired result using the following in my roxygen comments:
#noRd

Rd file name conflict when extending a S4 method of some other package

Actual question
How do I avoid Rd file name conflicts when
a S4 generic and its method(s) are not necessarily all defined in the same package (package containing (some of) the custom method(s) depends on the package containing the generic) and
using roxygenize() from package roxygen2 to generate the actual Rd files?
I'm not sure if this is a roxygen2 problem or a common problem when the generic and its method(s) are scattered across packages (which IMHO in general definitely is a realistic use-case scenario if you follow a modular programming style).
What's the recommended way to handle these situations?
Illustration
In package pkga
Suppose in package pkga you defined a generic method foo and that you've provided the respective roxygen code that roxygenize() picks up to generate the Rd file:
#' Test function
#'
#' Test function.
#'
#' #param ... Further arguments.
#' #author Janko Thyson \email{janko.thyson##rappster.de}
#' #example inst/examples/foo.R
#' #docType methods
#' #rdname foo-methods
#' #export
setGeneric(
name="foo",
signature=c("x"),
def=function(
x,
...
) {
standardGeneric("xFoo")
}
)
When roxygenizing() your package, a file called foo-methods.Rd is created in the man subdirectory that serves as the reference Rd file for all methods that might be created for this generic method. So far so good. If all of the methods for this generic are also part of your package, everything's good. For example, this roxygen code would make sure that documentation is added to foo-methods.Rd for the ANY-method of foo:
#' #param x \code{ANY}.
#' #return \code{TRUE}.
#' #rdname foo-methods
#' #aliases foo,ANY-method
#' #export
setMethod(
f="foo",
signature=signature(x="ANY"),
definition=cmpfun(function(
x,
...
) {
return(TRUE)
}, options=list(suppressAll=TRUE))
)
However, if package pkga provides the generic for foo and you decide in some other package (say pkgb) to add a foo-method for x being of class character, then R CMD check will tell you that there is a name clash with respect to Rd file names and/or aliases (as there already exists a Rd file foo-methods.Rd in pkga):
In package pkgb
#' #param x \code{character}.
#' #return \code{character}.
#' #rdname foo-methods
#' #aliases foo,character-method
#' #export
setMethod(
f="foo",
signature=signature(x="character"),
definition=cmpfun(function(
x,
...
) {
return(x)
}, options=list(suppressAll=TRUE))
)
To be more precise, this is the error that's thrown/written to file 00install.out
Error : Q:/pkgb/man/foo-methods.Rd: Sections \title, and \name must exist and be unique in Rd files
ERROR: installing Rd objects failed for package 'pkgb'
Due dilligence
I tried to change the values for #rdname and #aliases to foo_pkgb* (instead of foo*), but \title and \name still are set to foo when roxygenizing and thus the error remains. Any ideas besides manually editing the Rd files generated by roxygenize()?
EDIT 2012-12-01
In light of starting the bounty, the actual question might get a slightly broader flavor:
How can we implement some sort of an "inter-package" check with respect to Rd files and/or how can we consolidate S4 method help files scattered across packages into one single Rd file in order to present a single source of reference to the end-user?
The basic question is indeed "roxygenize"-only.
That's why I never had seen the problem.
While there are good reasons for the roxygenizing approach of package development,
I still see a very good reason not to go there:
Plea for much less extreme roxygenation
The resulting help pages tend to look extremely boring, not only the auto generated *.Rd files but also the rendered result.
E.g.
examples are often minimal, do not contain comments, are often not well formatted (using space, / new lines /..)
Mathematical issues are rarely explained via \eqn{} or \deqn{}
\describe{ .. } and similar higher level formatting is rarely used
Why is that? Because
1) reading and editing roxygen comments is so much more
"cumbersome" or at least visually unrewarding
than reading and editing *.Rd files in ESS or Rstudio or (other IDE that has *.Rd support built in)
2) If you are used that documentation
is the thing that's automatically generated at the end of your package building/checking
you typically tend to not considerung well written R documentation as something important
(but rather your R code, to which all the docs is just a comment :-)
The result of all that: People prefer writing documentation about their functions in vignettes or even blogs, github gists, youtube videos, or ... where it is very nice at the time of authoring, but is
pretty much detached from the code and bound to get outdated and withering (and hence, via Google search misleading your useRs)
--> The original motivation of roxygen of having code and documentation in the same place is entirely defeated.
I like roxygen and use it extensively at the time I create a new function...
and I keep and maintain it as long as my function is not in a package, or is not exported.
Once I decide to export it,
I run (the ESS equivalent of) roxygenize() once
and from then on take the small extra burden of maintaining a *.Rd file that is well formatted, contains its own comments (for me as author), has many nice examples, has its own revision control (git / svn / ...) history, etc.
I managed to generate NAMESPACE and *.Rd files for S4 methods for generics defined in another package than mine.
It took me the following steps:
Create NAMESPACE by hand as a workaround to a known roxygen2 bug.
Writing a NAMESPACE by hand is not so difficult at all!
Switch off NAMESPACE generation by roxygen2 in RStudio:
Build > more > Configure build tools > configure roxygen > do not use roxygen2 to generate NAMESPACE.
import the package containing the generic and export the S4 methods using exportMethods.
Write separate roxygen2 documentation for each of the S4 methods. Do not combine roxygen2 documentation (as I generally do for different methods of the same generic).
Add explicit roxygen tags #title and #description to the roxygen documentation of the S4 methods. Write #description explicitly, even if its value is identical as #title.
That makes it work for me.

How to properly document S4 methods using roxygen2

I've seen some discussions in SO and other places regarding how this should be or will be done in future versions of Roxygen2. However, I am stuck. How should I go about documenting a S4 generic, as well as its methods, using Roxygen2? A working example for a brand new generic/methods, as well as an example for extending base S4 generic would be incredibly useful. I do not want to have to make separate (mostly) redundant documentation for each S4 method of the same generic.
Due dilligence:
I have tracked down a useful example for the "extract" method. However, it appears to be outdated and incomplete for my question. It uses #slot tag in the class documentation, which is not (no longer?) supported. It only shows an extension of a core S4 method "[", rather than a complete Roxygen example including the documentation of the S4 generic.
How to properly document S4 "[" and “[<-“ methods using roxygen?
If I fully document a new S4 generic with title, description #param #return #name #aliases
#docType #rdname, and then document the S4 method with just the corresponding #name #aliases
#docType #rdname, I get the following R CMD check warning:
* checking for missing documentation entries ... WARNING
Undocumented S4 methods:
<< long list of apparently undocumented methods. E.g. generic 'plot' and siglist 'myClass1,ANY' >>
All user-level objects in a package (including S4 classes and methods)
should have documentation entries.
It looked at first as though none of my S4 methods documented in this fashion with roxygen2 had actually worked. However, so far, I've noticed that my extensions of the core method "show" do not have an associated error, even though they were documented in exactly the same way as the rest. Here is an example of the complete roxygen documentation I included above one of the show methods, that did NOT generate the missing-documentation error:
#' #name show
#' #aliases show,myClass2-method
#' #docType methods
#' #rdname show-methods
Thus, I'm at a loss. As you can see, I've included the convention for aliases for S4 methods described in the S4 documentation section of the R package manual, namely that methods should have an alias with the following name (without space):
generic,signature_list-method.
Somehow, this is not completely being understood by R CMD check.
Finally, after building the documentation using:
library("devtools")
library("roxygen2")
document("mypkgname")
check_doc("mypkgname")
and building the package, I get functioning documentation. Any titles from a specific method's documentation winds up in the 'Description' field, rather awkwardly. So roxygen2 obviously did something with each method's documentation and is on the right track. However, it is not enough to avoid a large and troubling warning from
> R CMD check mypkgname
I've looked at the Rd files, but I know even less about them to quickly see what's the problem is, and I anyway want to know the roxygen2 solution so that I will not have to manipulate the Rd files directly after each documentation revision.
So this is a multipart question:
What is the current recommended approach for both S4 generic and S4 method documentation with roxygen2?
Is there a good example available somewhere that shows the complete details?
What might be the cause, and solution, to the warning that documentation for most S4 methods is missing (even though the methods with "missing" documentation actually have had their doc parsed by roxygen2 and the resulting Rd files are at least good enough to work in the package after R CMD build mypkgname) ?
Official Support, explained in devtools doc
http://r-pkgs.had.co.nz/man.html#man-classes
(scroll down to the S4 subsection).
The current short example from that page is reproduced in the following (for convenience):
#' An S4 class to represent a bank account.
#'
#' #slot balance A length-one numeric vector
Account <- setClass("Account",
slots = list(balance = "numeric")
)
The above link very clearly explains S3, S4, and RC support via roxygen/devtools. The explanation there should be considered to supersede the older answer below, which does work for now, but is less clear and more complicated.
The old answer
Here is an example that should work for most S4 methods.
For documenting S4 generics, I find the following three lines necessary in most of my generic headers:
#' #export
#' #docType methods
#' #rdname helloworld-methods
Where helloworld-methods is replaced with the_name_of_your_generic-methods. This will be the name of the Rd file that holds the documentation for the generic and all its methods. This naming convention is not required, but common and useful. The #export tag is necessary now that a namespace is required for your package and you want this method to be available to users of your package, not just other methods/functions in your package.
For documenting methods, I find that only 2 lines are necessary, providing the #rdname and #aliases tag. The #rdname statement should match exactly the one for the generic. The #aliases tag must adhere to a naming convention described in the official S4 documentation section of Writing R Extensions.
#' #rdname helloworld-methods
#' #aliases helloworld,character,ANY-method
There should be no spaces after the commas in the #aliases name. I don't know the exact rules surrounding when to add ,ANY to the end of the signature list. The pattern seems to be that the number of elements in all #aliases signature lists needs to match the number of elements in the longest signature vector among the methods. In the example below, one of the methods is defined with 2-element signature, and so R CMD check wasn't satisfied with the documentation unless ,ANY was added to the aliases tag of the other methods, even if their signature definition only has one element.
A complete example follows. I built this and it works with no documentation-level warnings from R CMD check testpkg, using a bug-fixed fork of a very recent devel version of roxygen2 (which I have made available). For quick installation of this fork on your system, use library("devtools"); install_github("roxygen", "joey711"). The most recent version of roxygen2 won't work this moment because of a quotation error (described in a separate answer), but I expect this will be incorporated very soon and my fork won't be necessary. For looking at this example in context of the rest of a package, and seeing the resulting documentation (Rd) files, I have made it available as a trivial test package on github called testpkg.
##############################################################
#' The title, in this case: Helloworld-ify the argument.
#'
#' Some additional details about this S4 generic and its methods.
#' The extra blank line between this section and the title is
#' critical for roxygen2 to differentiate the title from the
#' description section.
#'
#' #param x Description of \code{x}. The main argument in this
#' example. Most often has such and such properties.
#'
#' #param y Description of \code{y}. An argument that is rarely
#' used by \code{"helloworld"} methods.
#'
#' #param ... Additional argument list that might not ever
#' be used.
#'
#' #return A helloworld-ified argument. Oh, you'll see.
#'
#' #seealso \code{\link{print}} and \code{\link{cat}}
#'
#' #export
#' #docType methods
#' #rdname helloworld-methods
#'
#' #examples
#' helloworld("thisismystring")
#' helloworld(char2helloworld("thisismystring"))
#' helloworld(matrix(0,3,3))
#' helloworld(list(0,0,0))
#' helloworld(integer(0))
setGeneric("helloworld", function(x, y, ...){
cat("Hello World!")
cat("\n")
standardGeneric("helloworld")
})
#' #rdname helloworld-methods
#' #aliases helloworld,ANY,ANY-method
setMethod("helloworld", "ANY", function(x, y, ...){
cat(class(x))
})
#' #rdname helloworld-methods
#' #aliases helloworld,character,ANY-method
setMethod("helloworld", "character", function(x){
show(x)
})
#' #rdname helloworld-methods
#' #aliases helloworld,character,character-method
setMethod("helloworld", c("character", "character"), function(x, y){
show(x)
})
This example assumes that you don't need separate method-specific documentation because your methods haven't veered wildly from the behavior one would expect based on the generic doc. There are means in roxygen2 to handle that alternative case using the #usage tag, but the details would be better handled by a separate SO question.
So most of your documentation effort goes into the roxygen header above the generic definition. This has some basis in the code, since the generic should include all specific arguments that appear in any of the subsequently defined methods . Note that arguments that are handled as part of the ... in the argument list are not included and shouldn't be documented specifically, but the ... itself should be documented above the generic as well (see the full example below).
For further details on the basics of documenting functions, there is a wiki in progress, the old roxygen vignette, as well as the roxygen2 development site on github. There is also a SO question on R documentation with Roxygen in general.
I have tracked down that the answer to part (3) -- the not-so-missing documentation of S4 methods -- is because of quotation marks being added erroneously around the \alias tags when the S4 naming convention is used; most likely a bug resulting from text-handling of an alias that contains a comma as part of its name. This is still true of the latest version of roxygen2 at the time of this posting. I just posted a more thorough description of the bug with a reproducible example on the roxygen2 github page:
https://github.com/klutometis/roxygen/issues/40
Briefly,
#' #aliases show,helloworld-method
becomes
\alias{"show,helloworld-method"}
in the resulting Rd file. Removing the quotations removes the R CMD check warning, and the documentation builds and is functional in both cases.
I think parts (1) and (2) of this question (best practices; good examples) still stand open.

Resources