I'm putting together a package; for simplicity with one function and one vignette illustrating its use.
I was able to run R CMD check packagename with no difficulties before I tried adding the vignette.
The package has a functionfoo.R in the R directory of packagename (it makes a plot with base graphics).
The vignette, in the vignettes directory, (an .Rnw file) calls function foo like this:
<<fig1, fig=true, echo=true, include=true>>=
df0 <- data.frame(x1=rnorm(10))
foo(df0)
#
I'm tying to play 'by the rules' but running R CMD check packagename as usual gives:
When sourcing 'foo.R':
Error: could not find function "foo"
Execution halted
I've tried adding the following to the .Rnw file, which didn't help:
\begin{document}
\VignetteDepends{packagename}
I've also tried this with no success:
<<fig1, fig=true, echo=true, include=true>>=
df0 <- data.frame(x1=rnorm(10))
source("foo.R")
foo(df0)
#
Note that the NAMESPACE file already contains the following:
export(foo)
Questions:
Do I need to add a specific source() command in the .Rnw file every time I call a function from the package? If so, how do I specify the path (i.e. where is R CMD check starting from when checking the vignette?)
Or should I take the easy way out by adding the following to the DESCRIPTION file:
BuildVignettes: False
(As I'm able to build a .pdf from the existing .Rnw file).
I'm trying to follow the advice in Writing R extensions.
Your vignette needs to have library("mypkg") at the top so that your own functions, like foo, can be found. I believe this is because the vignette building runs in a clean environment so it doesn't know about your package or any other for that matter unless you bring it up.
If you have such a line already, put a minimal example of your vignette into your question, and include your sessionInfo() as we may need that to figure it out.
Related
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.
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)
I'm looking into R Markdown for documenting functions I regularly use. I will put them into an R Markdown file to document them and then be able to read my thinking behind the function if i come back to it months later
My question is, if i start a new R project, Is it possible to source the r markdown file and use the library of functions i have created just by calling them similarly to if i was sourcing a regular R file. I dont really wish to maintain two sets of function files
I appreciate this may be a beginners question but any help pointing to tutorials and the like would be greatly appreciated
Thanks
As was mentioned in the comments, you should probably create a package for this purpose. But if you insist on putting function definitions in scripts and document them using RMarkdown files, using read_chunk() from the knitr package might be the way to go.
Note that this approach differs slightly from what you requested. You wanted to have the function definition in the markdown file together with the documentation. And then you wanted to somehow source that file into your R script in order to use the function. I did not find a way to do this (even though it might be possible).
The alternative that I propose puts the function definition in its own R script, say fun.R. The Rmarkdown file then reads the function definition from fun.R and adds documentation. If you want to use the function in some other script, you can simply source fun.R (and not the markdown file). This still means that you have to maintain the code for the function definition only once.
So let me show this with an example. This is fun.R:
## ---- fun
fun <- function(x) x^2
The first line is an identifier that will be used later. The markdown file is as follows:
---
title: "Documentation of fun()"
output: html_document
---
This documents the function `fun()` defined in `fun.R`.
```{r,cache = FALSE}
knitr::read_chunk("fun.R")
```
This is the function definition
```{r fun}
```
This is an example of how to use `fun()`:
```{r use_fun}
fun(3)
```
The first chunk reads in fun.R using knitr::read_chunk. Later on, you can define an empty chunk that has the identifier that was used in fun.R as its name. This will act as if the contents of fun.R were written directly in this file. As you see, you can also use fun() in later chunks. This is a screenshot of the resulting html file:
In a script where you want to use fun() you simply add source("fun.R") to source the function definition.
You could also have several functions in a single R file and still document them separately. Simply put an identifier starting with ## ---- before each function definition and then create empty chunks referring to each one of the identifiers.
This is admittedly somewhat more complicated than what you asked for, because it involves two files instead of just one. But at least there is no redundancy
The klmr/modules package has been superseded by the box package by the same author. It is on CRAN. After the cat command below run these lines to display the roxygen2 help for add2.
box::use(./test)
box::help(test$add2)
Perhaps this is close enough -- you can use the github klmr/modules package (not the CRAN modules package) to combine roxygen2 documentation and code in a single file without creating a package. For example, after installing the modules package copy this to the clipboard and then paste it into the R console to create a single file module with embedded documentation. The subsequent code then imports it, runs a function from it and invokes help. See the documentation of the modules package for more info.
Note that this has the following advantages: (1) everything is in a single file, (2) if you later decide to move to using packages you can use the very same file in your package with roxygen2 -- no need to revise anything, (3) any learning of roxygen2 applies to packages too.
# create a file with our documentation and code
Lines <- "
#' Add two numbers.
#'
#' #param x the first number.
#' #param y the second number.
#' #return The sum.
#' #note This is just a simple example.
#'
#' This function is a simple example intended to show how to use the modules
#' package with roxygen2.
add2 <- function(x, y) x + y
"
cat(Lines, file = "test.R")
# now we can import it
# devtools::install_github("klmr/modules")
library(modules)
test <- import("test") # do not include the .R extension
test$add2(1, 2)
## [1] 3
# this will cause help page to appear
?test$add2
The knitr package has relatively recently added new notangle vignette engines, such as knitr::rmarkdown_notangle, that allow disabling of evaluation of vignette chunks. The general process of using knitr for vignettes is described here, while the specific notangle functionality is described in an answer to this question.
My problem is that I can't get this to work. I can get it to pass R CMD build by including the .html output in the vignettes directory (I also put a copy in inst/doc), but I can't get it to pass R CMD check unless I specify --no-build-vignettes, or unless I change the rmarkdown_notangle engine back to rmarkdown.
I have built a trivial package that contains the following vignette (in vignettes/notangle.rmd): it's available here.
<!--
%\VignetteEngine{knitr::rmarkdown_notangle}
%\VignetteIndexEntry{Supplementary Materials}
-->
A silly little vignette.
```{r}
2+2
```
My DESCRIPTION file includes
Suggests:
knitr,
VignetteBuilder: knitr
BuildVignettes: yes
When I try to run R CMD check I get
* checking re-building of vignette outputs ... NOTE
Error in re-building vignettes:
...
Error: processing vignette 'notangle.rmd' failed with diagnostics:
Failed to locate the ‘weave’ output file (by engine ‘knitr::rmarkdown_notangle’)
for vignette with name ‘notangle’. The following files exist in directory ‘.’:
‘notangle.rmd’
Using r-devel (2014-09-17 r66626), but also happens with 3.1.1.
The workaround (which I would strongly prefer to avoid) is to switch from R code chunks to generic code chunks (opens with triple-backtick, rather than triple-backtick+"r"), which Rmarkdown doesn't process.
I'm sure I'm doing something boneheaded. Any clues?
update: I can get what I need (stop all chunks from being evaluated) by explicitly adding eval=FALSE to the options of every chunk, but I'd still like to know what's going on ...
It is a bug in the current version of knitr, and it has been fixed in the development version 1.7.9, which will (hopefully) be v1.8 on CRAN in the future.
I'm using sweave package to make a report based on my R code. However, since some code chunks take too much time to process, I'm planning to use cacheSweave package to avoid this issue.
In cacheSweave's vignette, it says I need to specify a driver
Sweave("foo.Rnw", driver = cacheSweaveDriver)
However, I would like to keep using the "Compile PDF" button inside RStudio, so that it automatically runs Sweave command and pdflatex as well.
How do I tell RStudio to use that specific driver when calling Sweave function?
The expected result is that when I process the following ".Rnw" code twice (example based on code taken from cacheSweave's vignette), the second time will be much faster since data is cached.
\documentclass{article}
\begin{document}
\SweaveOpts{concordance=TRUE}
<cache=TRUE>>=
set.seed(1)
x <- local({
Sys.sleep(10)
rnorm(100)
})
results <- mean(x)
#
\end{document}
Sweave function help says *Environment variable SWEAVE_OPTIONS can be used to override the initial options set by the driver*. So I tried the following command in RStudio console,
Sys.setenv(SWEAVE_OPTIONS="driver=cacheSweaveDriver")
then "Compile PDF" twice again, but no success.
Solution:
As posted in this "ghost" blog, I created a file named .Rprofile in my working directory with the following content:
library(utils)
library(cacheSweave)
assignInNamespace("RweaveLatex", cacheSweave::cacheSweaveDriver, "utils")
Trying to write my second Latex file
\documentclass{article}
\title{simple Sweave script}
\usepackage{/Users/Brenden/Documents/R/R-2.15.1/share/texmf/tex/latex/Sweave}
\begin{document}
\maketitle
This is a simple script to demonstrate Sweave. Let's
begin by generating some results
<<>>=
x=rnorm(30)
y=rnorm(30)
mean(x)
cor(x,y)
#
and follow that up with some random text
\end{document}
File saved with .Rnw as extension. I could then use Sweave under R to convert the file to tex. I then run pdflatex under cmd to get my .pdf file. R is stored under /Users/Brenden/Documents. MiKTex is stored under /Users/Brenden/Desktop.
It is said that usually the line of "usepackage" is not needed, as when I run Sweave under R, a line of "usepackage{Sweave}" will be added to the tex file which is stored under /Users/Brenden/Documents. However, if I don't put in userpackage line, when I run pdflatex under cmd (either under /Documents or /Desktop), I got a messsage that says "Sweave.sty not found". So I have been through this trouble by always adding a line of usepackage with a detailed path to help circumvent the problem. Although the "Sweave.sty not found" problem is circumvented, I do notice that when I run pdflatex under cmd, I got the response
LaTeX Warning: You have requested package '/Users/Brenden/Documents/R/R-
2.15.1/share/texmf/tex/latex/Sweave', but the package provides "Sweave'.
Then it runs through several files with .sty under MiKTex
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\base\ifthen.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\graphicx.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\keyval.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\graphics.sty)
(C:\Users\Brenden\Desktop\MiKTex\tex\latex\graphics\trig.sty)
...
to eventually create a .pdf
From another post on Stackoverflow, it is said, "That path is set automatically when you install LaTeX; it's your personal texmf tree and you can put any style or class files you want LaTeX to find there. The directory names don't matter, it searches recursively in them for Sweave.sty". To me, however, clearly my MiKTex could not find the Sweave.sty unless I specify the path. And even with the path specification, LaTex still gives me a warning. Could someone explain to me where I screwed up (during installing MiKTex, perhaps? ) so that I could help MiKtex find its way to Sweave without my specifying the path?
Thank you.
In the MiKTeX Settings program, there is a tab called "Roots". It is there that you can specify where additional .sty files can be found. In your case, I believe that you will want to add C:\Users\Brenden\Documents\R\R-2.15.1\share\texmf as an additional root. Doing this, any of the TeX programs will be able to find Sweave.sty whether run from inside R or from the command line.
It is annoying to be always distracted by little devils like this (new concept texmf tree, endless environment variables TEXINPUTS, SWEAVE_STYLEPATH_DEFAULT, ...). You will never worry about LaTeX packages if you use knitr, and if you like the Sweave style, you can simply put render_sweave() in the document like:
\documentclass{article}
\title{simple Sweave script}
<<setup, include=FALSE>>=
render_sweave()
#
\begin{document}
\maketitle
This is a simple script to demonstrate Sweave. Let's
begin by generating some results
<<>>=
x=rnorm(30)
y=rnorm(30)
mean(x)
cor(x,y)
#
and follow that up with some random text
\end{document}
Save it as, say, test.Rnw and compile it with
library(knitr); knit('test.Rnw') # or knit2pdf('test.Rnw')
And I guess you are probably better off without render_sweave() (i.e. use the default LaTeX style in knitr).
I suspect the path referred to in the other post is the path to your personal texmf tree, which is not where Sweave puts it. One option is to move it to your personal texmf tree, but the usual method nowadays, I believe, is to run pdflatex from within R, like this:
texi2dvi("foo.tex", pdf = TRUE)
I think you can also have Sweave add the full path automatically by adding
export SWEAVE_STYLEPATH_DEFAULT="TRUE"
to your .bashrc file, or whatever the equivalent would be on your system.
At the command line, R CMD sets up the environment with variables appropriate for running R, for instance on Windows
C:\Users\mtmorgan> "c:\Program Files\R\R-2.15.1\bin\R" CMD set
includes (this is not found if one types set at the command line)
TEXINPUTS=.;c:/PROGRA~1/R/R-215~1/.1/share/texmf/tex/latex;
and so
C:\Users\mtmorgan> "c:\Program Files\R\R-2.15.1\bin\R" CMD pdflatex myfile.tex
will find Sweave.sty. Also, tools::texi2dvi can be invoked from within R.
I eventually end up with the following solution:
install.packages("tinytex")
require("tinytex")}
install_tinytex(force = TRUE)
Sweave( "Report.Rnw" , encoding = "utf8" )
xelatex('Report.tex')
This code install TinyTex, then you can compile with pdflatex(), xelatex() or lualatex().