让knitr运行r脚本:我使用read_chunk还是source?

时间:2013-03-19 14:02:16

标签: r knitr rstudio

我正在使用RStudio版本0.97.312运行R版本2.15.3。我有一个脚本从各种来源读取我的数据并创建几个data.tables。然后我有另一个r脚本,它使用在第一个脚本中创建的data.tables。我想将第二个脚本转换为R降价脚本,以便分析结果可以作为报告输出。

我不知道read_chunk的目的,而不是source。我的read_chunk无效,但source正在运作。无论哪种情况,我都无法在RStudio的工作区面板中看到对象。

请解释read_chunksource之间的区别?我为什么要使用其中一个?为什么我的.Rmd脚本不起作用

这是一个荒谬简化的样本

它不起作用。我收到以下消息

  

错误:未找到对象'z'

两个简单的文件......

测试源到rmd.R

x <- 1:10
y <- 3:4
z <- x*y  

测试source.Rmd

Can I run another script from Rmd
========================================================

Testing if I can run "test of source to rmd.R"

```{r first part}
require(knitr)
read_chunk("test of source to rmd.R")
a <- z-1000
a
```

The above worked only if I replaced "read_chunk" with "source". I 
can use the vectors outside of the code chunk as in inline usage. 
So here I will tell you that the first number is `r a[1]`. The most 
interesting thing is that I cannot see the variables in RStudio 
workspace but it must be there somewhere.

3 个答案:

答案 0 :(得分:12)

read_chunk()只读取源代码(以供将来参考);它不像<{1}}一样评估代码。 source()以及this page解释了read_chunk()的目的。

答案 1 :(得分:0)

没有选项可以在knitr AFAIK中以交互方式运行块。但是,这可以通过以下方式轻松完成:

#' Run a previously loaded chunk interactively
#'
#' Takes labeled code loaded with load_chunk and runs it in the /global/ envir (unless otherwise specified)
#'
#' @param chunkName The name of the chunk as a character string
#' @param envir The environment in which the chunk is to be evaluated 
run_chunk <- function(chunkName,envir=.GlobalEnv) {
    chunkName <- unlist(lapply(as.list(substitute(.(chunkName)))[-1], as.character))    
    eval(parse(text=knitr:::knit_code$get(chunkName)),envir=envir) 
} 
NULL

答案 2 :(得分:0)

万一它对其他人有帮助,我发现使用read_chunk()来读取脚本而不评估它可以在两种方面有用。首先,如果您正在直接或交互地使用R脚本,则可能需要较长的加载程序包,数据等的代码前导。但是,例如,如果以前的代码块位于主文档已加载数据。

第二,您可能有一个包含很多块的脚本,并且想要控制哪些块在哪里运行(例如,特定位置的绘图或表格)。我想在脚本中运行所有内容时使用source(例如,在文档的开头加载自定义函数)。在文档的开头,我已经开始使用read_chunk来加载脚本,然后在需要的地方有选择地运行我想要的块。