What Is the Knitr Equivalent of 'R Cmd Sweave Myfile.Rnw'

What is the knitr equivalent of `R CMD Sweave myfile.rnw`?

The general solution (works regardless of the R version):

Rscript -e "library(knitr); knit('myfile.Rmd')"

Since R 3.1.0, R CMD Sweave has started to support non-Sweave documents (although the command name sounds a little odd), and the only thing you need to do is to specify a vignette engine in your document, e.g.

%\VignetteEngine{knitr::knitr}

To see the possible vignette engines in knitr, use

library(knitr)
library(tools)
names(vignetteEngine(package = 'knitr'))
# "knitr::rmarkdown" "knitr::knitr" "knitr::docco_classic" "knitr::docco_linear"

What exactly does R CMD Sweave --pdf do?

Thanks for the question. I had wondered myself about the code behind that 'automagical' process.

R CMD Sweave --pdf ultimately calls tools::texi2dvi, which:

Run[s] latex and bibtex until all cross-references are resolved and
create[s] either a dvi or PDF file.

(See here for more texi2dvi details).

Here is the chain of events set into motion by an R CMD Sweave --pdf call:

  • The source file rcmdfn.c has code that instructs R CMD Sweave to run utils:::.Sweave() --args" through Rterm.exe.

  • If --pdf is set, utils:::.Sweave() calls tools::texi2pdf() to process the Sweave file.

  • texi2pdf() in turn calls tools::texi2dvi().

  • Finally, texi2dvi() looks at the environment to learn which tools are available to it, and does the work described in the help file linked above.

Run Sweave or knitr with objects from existing R session

I think it just works. If your Sweave file is named "temp.Rnw", just run

> x <- 5
> Sweave("temp.Rnw")

You'll have to worry about naming the resulting output properly so each report doesn't get overwritten.

Formatted scientific names from R to LaTeX (using Sweave or knitr)

What I imagine that you are doing is this:

<<example, echo=FALSE>>=
library(taxlist)
data(Easplist)
\Sexpr{print_name(Easplist, 206, style="markdown")}
@

Simply move the \Sexpr{}to outsite the chunk.

<<example, echo=FALSE>>=
library(taxlist)
data(Easplist)
@

\Sexpr{print_name(Easplist, 206, style="markdown")}

That will output you what you want.

EDIT:

If you are trying to incorporate "latex" as a style option for the output, then it should look like this when it outputs outside of latex:

library(taxlist)
data(Easplist)
print_name(Easplist, 206, style="latex")
[1] "\\textit{Cyperus papyrus} L."

The "\" will escape the escape. I did not incorporate it into your function, but here is an example:

<<>>=
example_text <- "Cyperus papyrus L."
example_text <- strsplit(example_text, split = " ")
test1 <- paste0("\\textit{", example_text[[1]][1], " ", example_text[[1]][2], "}",
" ", example_text[[1]][3])
@

\Sexpr{test1} is a paper reed.

The output looks like this in the rendered pdf.

Sample Image

Control width of knitr output for columns in sweave documents

Options should be passed like this:

<<echo=FALSE>>=
opts_chunk$set(comment="", message=FALSE,tidy.opts=list(keep.blank.line=TRUE, width.cutoff=120),options(width=100), cache=TRUE,fig.align='center',fig.height=6, fig.width=10,fig.path='figure/beamer-',fig.show='hold',size='footnotesize', cache=TRUE)
@

And here you specify width.cutoff for code and width for r results.

Extracting arguments of an R function to use in knitr

I had written a function and posted it as an answer earlier (as noted in the question itself), but wasn't entirely happy with the inconsistencies or the requirement that it had to be used with "markdown" to be used successfully. After a little bit more work, this is the function that I came up with:

helpExtract <- function(Function, section = "Usage", type = "m_code", ...) {
A <- deparse(substitute(Function))
x <- capture.output(tools:::Rd2txt(utils:::.getHelpFile(help(A, ...)),
options = list(sectionIndent = 0)))
B <- grep("^_", x) ## section start lines
x <- gsub("_\b", "", x, fixed = TRUE) ## remove "_\b"
X <- rep(FALSE, length(x))
X[B] <- 1
out <- split(x, cumsum(X))
out <- out[[which(sapply(out, function(x)
grepl(section, x[1], fixed = TRUE)))]][-c(1, 2)]
while(TRUE) {
out <- out[-length(out)]
if (out[length(out)] != "") { break }
}

switch(
type,
m_code = c("```r", out, "```"),
s_code = c("<<>>=", out, "@"),
m_text = paste(" ", out, collapse = "\n"),
s_text = c("\\begin{verbatim}", out, "\\end{verbatim}"),
stop("`type` must be either `m_code`, `s_code`, `m_text`, or `s_text`")
)
}

Quite a mouthful, and it's not entirely DRY... but I wanted to capture four scenarios and this was the quickest idea that came to mind. The four scenarios I anticipate are:

  1. Document type is markdown and user is extracting a code block (type = "m_code")
  2. Document type is markdown and user is extracting a non-code section (type = "m_text")
  3. Document type is Sweave and user is extracting a code block (type = "s_code")
  4. Document type is Sweave and user is extracting a non-code section (type = "s_text")

The function extracts the output of Rd2txt. I picked that over the other formats (HTML, LaTeX) to allow me to use a single function to get what I was after and not have to create multiple functions.


Usage

Usage is different depending on if you're creating a "Sweave" (.Rnw) or a "markdown" (.Rmd) document.

  1. Markdown

    Insert your code in a code chunk that looks something like this (maybe one day I'll add different methods, but not now):

    ```{r, echo=FALSE, results='asis'}
    cat(helpExtract(cor), sep = "\n")
    ```
  2. Sweave

    Pretend you are inserting a "child" document that should be included in the main document using Sexpr{knit_child(.)}

    \Sexpr{knit_child(textConnection(helpExtract(cor, type = "s_code")), 
    options = list(tidy = FALSE, eval = FALSE))}

I've created a Gist that includes the function, a sample Rmd file and an sample Rnw file. Feel free to leave comments and suggestions here on Stack Overflow (since Gist comments are pretty much meaningless since they don't notify the user when a comment is posted).


If you're trying to refer to a function from a package that is not currently loaded, the usage of helpExtract should be something like:

helpExtract(gls, package = "nlme")

Can Sweave produce many pdfs automatically?

You can use something like a for loop with a global variable changing, which controls which city you want to weave into the report; see the other post Run Sweave or knitr with objects from existing R session

The code will be like (suppose cities is a character vector, and I use the knitr package as an example because you can specify the filename of the output):

for (city in cities) {
knit('city_template.Rnw', output = paste('report_', city, '.tex', sep = ''))
}

Inside city_template.Rnw, you have a chunk like

<<do-my-job>>=
make_plot(city, ...)
whatever(city, ...)
@

Then you will get a series of tex files named by the cities, and the rest of your job is to compile them to PDF (not possible for RStudio to compile multiple tex files, AFAIK, but it is trivial to do it in command line or in R with texi2dvi()).

There is one thing you need to be careful -- you have to use a different figure prefix (the option fig.path) for each output file, otherwise different cities can override each other's figure output. In knitr, this can be done by like this:

<<setup, echo=FALSE>>=
opts_chunk$set(fig.path = paste('my-prefix-', city, sep = ''))
@

I believe this should be safe to produce many reports with a loop.

BTW, you can certainly achieve the same goal with Sweave; perhaps you will know why I developed knitr later (this is off-topic, so I won't expand here).



Related Topics



Leave a reply



Submit