嵌入但不在Rmarkdown中运行R脚本 [英] Embed but don't run R scripts in Rmarkdown

查看:553
本文介绍了嵌入但不在Rmarkdown中运行R脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆