Passing values from an Rnw file to an R script - r

Since I am a newbie as far as knitr is concerned, I am reading and modifying the examples given in knitr web site. One the approaches that caught my attention is to call chunks of an R script within an Rmw file. After compiling and modifying several examples, I wonder whether one can set a variable on an Rmw file and pass it to an R-script.
Here is an example
\documentclass{article}
\begin{document}
<<set-options, echo=FALSE, cache=FALSE>>=
options(replace.assign=TRUE)
opts_chunk$set(cache=TRUE, fig.show='asis')
read_chunk('simple_example.R')
#
\title{Example}
\author{Somebody}
\maketitle
\section{Print variable}
<<Print-data, echo=TRUE>>=
inp=2
#
\end{document}
and
# Simple Example
## ---- Print-data ----
inp=inp+2
print(inp)
The output result is ip=2 and an error msg "object inp not found".
Many thanks

The code chunk Print-data overrode the one in the Rnw file, so inp=2 was not executed, hence the error.
It seem you want to embed the chunk after Print-data:
<<>>=
inp=2
<<Print-data>>
#

Related

why suppress Error in Rmarkdown doesn't work?

I want to supress Errors in Rmw files. So, i've tried to set the global chunk option error=TRUE, but it doesn't work. Also it doesn't work to set the chunk option error=TRUE directly in the chunk.
Here is an example code:
\begin{document}
\SweaveOpts{concordance=TRUE}
abc
<<setup, cache=F, include=F>>=
library(knitr)
library(formatR)
opts_chunk$set(error=TRUE)
knit_hooks$set(error=TRUE)
#
<<a,error=TRUE>>=
A <- 5
# of course, that doesnt work, but i want the error message as chunk output
A * B
#
\end{document}
I don't understand why it doesn't work
Only the error message:
"Error in eval(expr, .GlobalEnv) : object 'L' not found"
appears.
You seem to be using Sweave from base R rather than knitr. If you were using knitr, you'd get a warning about the \SweaveOpts{concordance=TRUE} statement.
If you are using RStudio, this is one of the Project Options. If you are running things directly, run knitr::knit("<your filename>"), instead of Sweave("<your filename>").
There are a couple of other errors that will stop knitr from working; this version fixes them:
\documentclass{article}
\begin{document}
abc
<<setup, cache=F, include=F>>=
library(knitr)
library(formatR)
opts_chunk$set(error=TRUE)
#
<<a,error=TRUE>>=
A <- 5
# of course, that doesnt work, but i want the error message as chunk output
A * B
#
\end{document}
The changes were:
You need the \documentclass line at the start.
You don't want the \SweaveOpts{concordance=TRUE} statement.
You don't want the knit_hooks$set(error=TRUE) statement.

R Sweave: put the whole code of the .Rnw file in Appendix?

I just found this awesome technique to put the code used in the .Rmd file in the appendix (of that same file).
However, I am using R Sweave and not R Markdown and I would like to know if there exists a similar way to put all the code at the end in a unique chunk. The code to do that in Markdown does not work in Sweave. I precise that, unlike this post, I do not have a separate .R file where the calculations are made. Everything is done in the .Rnw file.
Does anybody know how to do it?
Edit : a reproducible example
\documentclass[11pt, twocolumn]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\begin{document}
\SweaveOpts{concordance=TRUE}
<<reg2, echo=FALSE, print=FALSE>>=
head(mtcars)
#
<<reg3, echo=FALSE, print=FALSE>>=
head(iris)
#
\section*{Appendix}
% the place where I could like to put the whole code
\end{document}
This chunk works to include the code:
<<echo=FALSE, eval=TRUE>>=
filename <- tempfile(fileext=".R")
Stangle("test.Rnw", output = filename, quiet = TRUE)
cat(readLines(filename), sep = "\n")
#
When I include that in your example file, I see this:
I think it's possible to modify the format a bit; see ?Rtangle for some details. Similar things are possible with knitr, but it's more flexible. I suspect the best method would be similar to the one you found for RMarkdown.

Using R Markdown chunks in R Sweave(Knitr)

I have a R Markdown file that has my notes and chunks of code. I now want to write a R Sweave(Knitr) document to publish a paper using those chunks. I do not want to cut and paste the chunks, I rather call them directly. That way if I update the chunks, I don't have to do it in two places. It seems like it would be simple enough, but I can not figure it out. My code is as follows, test.rmd is my mark down document, foo is the chunk in the rmd file.
Test.rnw
<<Setup>>===
read_chunk('test.rmd')
#
<<foo>>==
#
Test.rmd
```{r foo, echo=TRUE}
print(summary(cars))
```
I would expect a summary of cars to be displayed in the output of the compilation of test.rnw into a PDF. But I don't. Any help is greatly appreciated.
read_chunk reads chunks from r script so call purl before read_chunk:
<<Setup>>=
knit_patterns$set(all_patterns[["md"]])
purl("test.Rmd")
knit_patterns$set(all_patterns[["rnw"]])
read_chunk("test.R")
#
<<foo>>=
#

Show code in appendix using knitr

I have an Rnw file (a large one) and I want to show all code used in an appendix.
It is suggested in some of the knitr examples (https://github.com/yihui/knitr-examples/blob/master/073-code-appendix.Rnw, also a good MWE) that having a code block like this is the way:
<<Rcode, eval=FALSE, ref.label=all_labels()[-1],echo=TRUE, cache=FALSE>>=
#
This works fine except all the code chunks merge into each other and none are labelled.
On the other hand if I run purl(myfile.Rnw) it labels the code chunks and separates them by two lines, which makes things much easier to read.
Is there any way of automatically listing the code using the second approach in a report appendix? I know I can have a code chunk to run purl to produce myfile.R as part of my report, but how do I then show the code in myfile.R in my appendix?
Here's an example .Rnw file (called "example.rnw"):
\documentclass{article}
\begin{document}
<<a>>=
x <- 1:10
x
#
<<b>>=
y <- 10:1
y
#
<<c>>=
z <- 1:5
z
#
\clearpage
\input{example-purl.tex}
\end{document}
If you create a file in your working directory called "template.rnw" that just contains:
<<%sCHUNK_LABEL_HERE, eval=FALSE>>=
#
Then, you run:
stitch(purl("example.rnw",output="example-purl.r"),template="template.rnw")
knit("example.rnw")
Does that make sense? Basically, you're purling, stitching the purled code, knitting the original document, and then compiling the resulting LaTeX ("example.tex") that includes the knitting and purling. Everything should be formatted nicely (and consistently).

Is it possible to include a Sexpr before the expression has been evaluated in Sweave / R?

I'm writing a Sweave document, and I want to include a small section that details the R and package versions, platofrms and how long ti took to evalute the doucment, however, I want to put this in the middle of the document !
I was using a \Sexpr{elapsed} to do this (which didn't work), but thought if I put the code printing elapsed in a chunk that evaluates at the end, I could then include the chunk half way through, which also fails.
My document looks something like this
%
\documentclass[a4paper]{article}
\usepackage[OT1]{fontenc}
\usepackage{longtable}
\usepackage{geometry}
\usepackage{Sweave}
\geometry{left=1.25in, right=1.25in, top=1in, bottom=1in}
\begin{document}
<<label=start, echo=FALSE, include=FALSE>>=
startt<-proc.time()[3]
#
Text and Sweave Code in here
%
This document was created on \today, with \Sexpr{print(version$version.string)} running
on a \Sexpr{print(version$platform)} platform. It took approx sec to process.
<<>>=
<<elapsed>>
#
More text and Sweave code in here
<<label=bye, include=FALSE, echo=FALSE>>=
odbcCloseAll()
endt<-proc.time()[3]
elapsedtime<-as.numeric(endt-startt)
#
<<label=elapsed, include=FALSE, echo=FALSE>>=
print(elapsedtime)
#
\end{document}
But this doesn't seem to work (amazingly !)
Does anyone know how I could do this ?
Thanks
Paul.
This works just fine for me:
\documentclass{article}
\usepackage{Sweave}
\begin{document}
<<label=start, echo=FALSE, include=FALSE>>=
startt<-proc.time()[3]
#
Text and Sweave Code in here
This document was created on \today, with
\Sexpr{print(version$version.string)}.
<<results=hide,echo=FALSE>>=
Sys.sleep(2) # instead of real work
#
More text and Sweave code in here
<<label=bye, include=FALSE, echo=FALSE>>=
endt<-proc.time()[3]
elapsedtime<-as.numeric(endt-startt)
#
It took approx \Sexpr{elapsedtime} seconds to process.
\end{document}
I had to remove the version string inside the \Sexp{} as I get an underscore with via x86_64 which then upsets LaTeX. Otherwise just fine, and you now get the elapsed time of just over the slept amount.
You could use either R to cache the elapsed time in a temporary file for the next run, or pass it to LaTeX as some sort of variable -- but you will not be able to use 'forward references' as the R chunks gets evaluated in turn.
btw you don't usually need print to evaluate variables R
\Sexpr{version$version.string}
works fine as well
Dirk's answer is almost perfect, but still doesn't let you put the answer half way through the document. I got quite frustrated thinking it should work, but realised that the code I had was opening the time file at the start of each run (and emptying it) and writing the empty result into my document, then putting the answer in the time file at the end !
I eventually did something similar but using R to only open and write the file at the end, which worked great !;
\documentclass[a4paper]{article}
\usepackage[OT1]{fontenc}
\usepackage{longtable}
\usepackage{geometry}
\usepackage{Sweave}
\geometry{left=1.25in, right=1.25in, top=1in, bottom=1in}
\begin{document}
<<label=start, echo=FALSE, include=FALSE>>=
startt<-proc.time()[3]
#
Text and Sweave Code in here
%
This document was created on \today, with \Sexpr{print(version$version.string)} running
on a \Sexpr{print(version$platform)} platform. It took approx \input{time}
sec to process.
More text and Sweave code in here
<<label=bye, include=FALSE, echo=FALSE>>=
odbcCloseAll()
endt<-proc.time()[3]
elapsedtime<-as.numeric(endt-startt)
#
<<label=elapsed, include=FALSE, echo=FALSE>>=
fileConn<-file("time.tex", "wt")
writeLines(as.character(elapsedtime), fileConn)
close(fileConn)
#
\end{document}

Resources