Run Sweave or Knitr with Objects from Existing R Session

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.

Is there a way to knitr markdown straight out of your workspace using RStudio?

RStudio opens a new R session to knit() your R Markdown file, so the objects in your current working space will not be available to that session (they are two separate sessions). Two solutions:

  1. file a feature request to RStudio, asking them to support knitting in the current R session instead of forcibly starting a new session;
  2. knit manually by yourself: library(knitr); knit('your_file.Rmd') (or knit2html() if you want HTML output in one step, or rmarkdown::render() if you are using R Markdown v2)

Sweave in RStudio cannot find objects loaded in global environment

The code from the Sweave .Rnw document is run in a separate R session, so it does not have access to objects you've loaded or created in the console. You have to explicitly load the data in a Sweave code chunk in order for it to be accessible when you call summary.

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"

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.

Sweave can't see a vector if run from a function?

OK, I realise that my initial ideas of a 'simple, self contained example' wasn't particularly simple or usefull. So I redid my example and got a sort of answer for myself, although I'd love someone to exaplain why and even suggest a better solution,
Here's my example test_sweave.Rnw file

% 
\documentclass[a4paper]{article}
\usepackage[OT1]{fontenc}
\usepackage{Sweave}
\begin{document}

\title{Test Sweave Document}
\author{Paul Hurley}

\maketitle

<<>>=

if(exists("foo")){print(foo)}
ls()
Sys.time()
@
\end{document}

If I run this code;

testFoo<-function(){    
foo<-"My Test String"
Sweave("test_sweave.Rnw")
require(tools)
texi2dvi(file = "test_sweave.tex", pdf = TRUE)
}

rm(foo) testFoo()

my resulting file does NOT contain the contents of the string foo.

> if (exists("foo")) {
+ print(foo)
+ }
> ls()
[1] "testFoo"

If I run this code (i.e, the same thing, just run directly)

rm(foo)
foo<-"My Test String"
Sweave("test_sweave.Rnw")
require(tools)
texi2dvi(file = "test_sweave.tex", pdf = TRUE)

my resulting file does contain the foo string

> if (exists("foo")) {
+ print(foo)
+ }
[1] "My Test String"
> ls()
[1] "foo" "testFoo"

and if I run this code

testBar<-function(){
foo<<-"My Test String"
Sweave("test_sweave.Rnw")
require(tools)
texi2dvi(file = "test_sweave.tex", pdf = TRUE)
}

rm(foo)
testBar()

My resulting file also contains the foo string

> if (exists("foo")) {
+ print(foo)
+ }
[1] "My Test String"
> ls()
[1] "foo" "testBar" "testFoo"

So, it seems that sweave runs in the global environment, not in the environment it was called from. This means the only way to pass variables to sweave when sweave is run from a function is to use the <<- operator to put the variable in the global environment. (I think).

Anyone else want to comment who knows more about environments ?

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