External Lyx + knitr code implementation with read_chunk ('foo.R') not working

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

My Lyx setup compiled knitr_minimal.pdf from knitr_minimal.lyx without any problems.

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 value is \ Sexpr {mx}.

with this:

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

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

script minimal.R stored in the same directory and consists only of

 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 in order, but instead

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

I see

The first element of x is an error in eval (expr, envir, enc): object x was not found. Its value is an error in eval (expr, envir, enc): the mx object was not found.

I would be grateful for any advice.

+1
source share
1 answer

You need to add a label to your code in minimal.R corresponding to the block label in your LyX document, otherwise knitr does not know where to paste the code.

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

If you open the R script on the knitr web page , you will see several comment lines of the form ## @knitr label . I will refine the web page to clarify this. There is an alternative approach for labeling, which is documented in ?knitr::read_chunk .

The second problem with your LyX document is that you put read_chunk() in a boring-random block, but you really need to read the code before inserting it into a piece.

 <<setup>>= read_chunk('minimal.R') @ <<boring-random>>= @ 
+3
source

Source: https://habr.com/ru/post/1485301/


All Articles