Embed but don't run R scripts in Rmarkdown

旧街凉风 提交于 2020-05-17 07:06:40

问题


I am writing a paper in Rmarkdown about an ongoing project. I have my own .Rmd file where I am writing it.

At the same time, I have several scripts in R stored in different files with the extension .R.

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.

To summarize:

  • Folder 1
    • paper.Rmd
    • script1.R
    • script2.R

I tried this chunk with no success:

```{r eval=F}
source("script1.R")


回答1:


One option would be to readLines on the script instead of sourcing it.

Consider this trivial R script:

writeLines("foo <- function(x) x + 2", con = "foo.R")
system("cat foo.R")
# foo <- function(x) x + 2

Instead of using source use readLines.

exp <- readLines("foo.R")

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


来源:https://stackoverflow.com/questions/61486266/embed-but-dont-run-r-scripts-in-rmarkdown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!