嵌入但不在Rmarkdown中运行R脚本 [英] Embed but don't run R scripts in Rmarkdown
问题描述
我正在Rmarkdown中写一篇有关正在进行的项目的论文.我在编写文件时有自己的.Rmd
文件.
I am writing a paper in Rmarkdown about an ongoing project. I have my own .Rmd
file where I am writing it.
同时,我在R中有几个脚本,这些脚本存储在扩展名为.R
的不同文件中.
At the same time, I have several scripts in R stored in different files with the extension .R
.
在论文的不同部分中,我需要描述这些R脚本中的内容,因此需要在不运行该脚本的情况下将脚本代码嵌入Rmarkdown文件中.
In different parts of the paper I need to describe what it is in those R scripts, so that I need to embed the codes of the scripts in the Rmarkdown file without running it.
总结:
- 文件夹1
- paper.Rmd
- script1.R
- script2.R
- Folder 1
- paper.Rmd
- script1.R
- script2.R
我尝试了这个块,但没有成功:
I tried this chunk with no success:
```{r eval=F} source("script1.R")
推荐答案
一种选择是在脚本上使用
readLines
而不是采购它.One option would be to
readLines
on the script instead of sourcing it.考虑一下这个简单的R脚本:
Consider this trivial R script:
writeLines("foo <- function(x) x + 2", con = "foo.R") system("cat foo.R") # foo <- function(x) x + 2
使用
readLines
代替使用source
.exp <- readLines("foo.R")
现在您有了Rscript的文本.您可以使用
cat
进行打印.Now you have the text of the Rscript. You could use
cat
to print it.cat(exp) #foo <- function(x) x + 2
或者您可以对其进行评估.
Or you could evaluate it.
eval(parse(text=exp)) foo(2) #[1] 4
这篇关于嵌入但不在Rmarkdown中运行R脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!