Imagine, you define an R function to share with a pal, only a single function. In case of, you decide later to include this function in a package, you document it using Roxygen comments and tags (e. g. #' @name my_function
). Is it possible to produce a PDF from this single R file? If yes, how?
1) We will use the file lc.R as an example which we first download from github. First use kitten to create the boilerplate for a package. Copy lc.R to it. Then run document from devtools to roxygenize it and finally use Rd2pdf to create the pdf, lc.pdf .
library(devtools)
library(pkgKitten)
library(roxygen2)
# set up lc in lc.R to use as a test example
u <- "https://raw.githubusercontent.com/mailund/lc/master/R/lc.R"
download.file(u, "./lc.R")
# create package containing lc.R - ignore any NAMESPACE warnings
kitten("lc")
file.copy("lc.R", "./lc/R")
# roxygenize it generating an Rd file
document("lc")
file.copy("lc/man/lc.Rd", ".")
# convert Rd file to pdf
R <- file.path(R.home("bin"), "R")
cmd <- paste(R, "CMD Rd2pdf lc.Rd")
system(cmd, wait = FALSE)
2) There used to be a package on CRAN named document (or see gitlab) which does the same thing in one step but it was removed last year. Note that the document package depends on the fritools (or see gitlab) package which was also removed. The source of both are archived on CRAN and on gitlab and it may be possible to build them yourself. (Update June 14, 2023: The document and fritools packages are back on CRAN.)
library(document)
setwd("...dir containing lc.R ...")
if (!dir.exists("doc")) dir.create("doc")
document("lc.R", "doc", check = FALSE)
3) This approach does not create a PDF but it does allow one to view formatted help for a script converting it from the roxygen2 markup to HTML showing it in the browser. Note that the box package should not be attached, i.e. do not use a library(box)
statement. Assume that lc.R is in the current directory -- see the download.file statement in (1) above. The code below may generate warnings or errors but it still works to bring up the help for the lc function in lc.R showing it in the default browser.
box::use(./lc)
box::help(lc$lc)