使用read_chunk('foo.R')进行Lyx + knitr代码外部化失败 [英] Lyx+knitr code externalization with read_chunk('foo.R') fails
问题描述
我正尝试使用read_chunk()
从我的Lyx文件中分离我的R代码,如此处.
I am trying to use read_chunk()
to separate my R code from my Lyx file as explained here.
我的Lyx设置从 knitr_minimal.lyx
编译了knitr_minimal.pdf
没有任何问题.
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)
@
x的第一个元素是\ Sexpr {x [1]}.它的平均值是\ Sexpr {mx}.
The first element of x is \Sexpr{x[1]}. Its mean is \Sexpr{mx}.
与此:
<<boring-random, cache=FALSE>>=
read_chunk('minimal.R')
@
x的第一个元素是\ Sexpr {x [1]}.它的平均值是\ Sexpr {mx}.
The first element of x is \Sexpr{x[1]}. Its mean is \Sexpr{mx}.
脚本minimal.R
保存在同一目录中,并且仅由
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)
我将修改后的文件另存为knitr_minimal1.lyx
并进行了编译.文件knitr_minimal1.pdf
可以编译,但是可以代替
I saved the modified file as knitr_minimal1.lyx
and compiled it. The file knitr_minimal1.pdf
compiled alright, but instead of
x的第一个元素是0.145.平均值是0.3217.
The first element of x is 0.145. Its mean is 0.3217.
我知道
x的第一个元素是eval中的错误(expr,envir,enclos):找不到对象"x".其平均值是eval(expr,envir,enclos)中的错误:找不到对象"mx".
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.
推荐答案
您必须在minimal.R
中的代码中添加与LyX文档中的块标签相对应的标签,否则knitr
不知道在哪里插入代码.
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)
如果您在knitr
网页中打开R脚本,则会看到## @knitr label
形式的多行注释.我将更新网页以澄清这一点. ?knitr::read_chunk
中记录了另一种指定标签的方法.
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
.
LyX文档的第二个问题是将read_chunk()
放在boring-random
块中,但是您确实需要先阅读代码 ,然后再将其插入到块中.
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>>=
@
这篇关于使用read_chunk('foo.R')进行Lyx + knitr代码外部化失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!