Use RStudio and the devtools package. It's easier.
install.packages("devtools")
In RStudio, File -> New Project -> New Directory -> R Package, with a name:
Go to Build -> Configure Build Tools
Add --as-cran to "Check Package" (useful later)
Click Generate documents with Roxygen. If that is gray, install roxygen2:
install.packages("roxygen2")
Click "Configure" - click all the boxes.
man folderroxygen2 will create the documentation automaticallyroxygen2 will create the documentation automaticallyIn the RStudio project, go to "Go to file/function" search bar on the menu bar.
Type "DESCRIPTION" and open that file.
Roxygen allows for functions and documentation in the same file. Let's make a function:
top = function(x, n) {
xx = x[1:n, 1:n]
hist(xx)
print(xx)
}
Save this to top.R file in R/ (where R functions are). Delete hello.R file.
Highlight the following code:
top = function(x, n) {
Go to Code -> Insert Roxygen Skeleton
Output:
#' Title #' #' @param x #' @param n #' #' @return #' @export #' #' @examples
Add @title and @description tags:
#' @title #' @description #' #' @param x #' @param n #' #' @return #' @export #' #' @examples
@param stands for a parameter/argument for that function.@return denotes what the function returns. This is required.@export - when people install your package, can they use this function@examples - code to show how the function works. Wrap functions in \dontrun{} if not wanted to run#' @title Print the top of a matrix
#' @description \code{top} is a small function to not just present the first rows
#' of a matrix, but also the first number of columns
#'
#' @param x a \code{matrix}
#' @param n Number of rows and columns to display of the matrix
#'
#' @return A \code{NULL}
#' @export
#'
#' @examples
#' mat = matrix(rnorm(100), nrow = 10)
#' top(mat, n = 4)
#' \dontrun{
#' top(mat, n = 10)
#' }
The NAMESPACE files tells the R package what to import and export. In Roxygen:
@export - adds this to the NAMESPACE file@import - in roxygen, if you want to import a package, you say @import PACKAGENAMElibrary(PACKAGENAME)@importFrom - in roxygen, if you want to import a function, you say @import PACKAGENAME func1 func2pkgA has function A and pkgB has functions A and B, if @import pkgA A, @import pkgB B, then if you call A(), R knows it's from pkgAbase package, includying anything from stats (e.g. quantile) or graphics (e.g. hist)Add @importFrom graphics hist to your top.R file