Question

I am trying to use read_chunk() to separate my R code from my Lyx file as explained here.

My Lyx setup compiled the knitr_minimal.pdf from knitr_minimal.lyx without any issues.

But then I tried to replace this:

<<boring-random>>=
set.seed(1121)
(x=rnorm(20))
mx <- mean(x)
vx <- var(x)
@

The first element of x is \Sexpr{x[1]}. Its mean is \Sexpr{mx}.

with this:

<<boring-random, cache=FALSE>>=
read_chunk('minimal.R')
@

The first element of x is \Sexpr{x[1]}. Its mean is \Sexpr{mx}.

The script minimal.R is saved in the same directory, and consists of just

set.seed(1121)
(x=rnorm(20))
mx <- mean(x)
vx <- var(x)

I saved the modified file as knitr_minimal1.lyx and compiled it. The file knitr_minimal1.pdf compiled alright, but instead of

The first element of x is 0.145. Its mean is 0.3217.

I see

The first element of x is Error in eval(expr, envir, enclos) : object ’x’ not found. Its mean is Error in eval(expr, envir, enclos) : object ’mx’ not found.

I'd be grateful for any advice.

Was it helpful?

Solution

You have to add a label to your code in minimal.R corresponding to the chunk label in your LyX document, otherwise knitr does not know where to insert the code.

## @knitr boring-random
set.seed(1121)
(x=rnorm(20))
mx <- mean(x)
vx <- var(x)

If you open the R script in the knitr web page, you will see several lines of comments of the form ## @knitr label. I will update the web page to clarify this. There is an alternative approach to specify the labels, which is documented in ?knitr::read_chunk.

The second problem of your LyX document is you put read_chunk() in the boring-random chunk, but you really need to read the code before you insert it into a chunk.

<<setup>>=
read_chunk('minimal.R')
@
<<boring-random>>=
@
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top