简体   繁体   English

重用R Markdown中的外部R脚本

[英]Reuse external R script in R Markdown

When using R Markdown, I would like to call an external R script to use values specified in the R Markdown file. 使用R Markdown时,我想调用一个外部R脚本以使用R Markdown文件中指定的值。

Ex. 例如

{r echo=FALSE, warning=FALSE, results='hide', message=FALSE} read_chunk('Analysis of Fulton_L_W relations_All_surveys.R') survey <- "A"

{r Analysis, echo=FALSE, results='hide', message=FALSE, warning=FALSE}

Then afterwards I'd like to respecify the indput variable and rerun the script 然后,我想重新指定indput变量并重新运行脚本

Ex. 例如

{r echo=FALSE, warning=FALSE, results='hide', message=FALSE} survey <- "B"

{r Analysis, echo=FALSE, results='hide', message=FALSE, warning=FALSE}

However, a duplicate lable error occurs. 但是,发生重复的标签错误。 But when I then use the options(knitr.duplicate.label = 'allow'), the second run of the analysis is not completed. 但是,当我随后使用options(knitr.duplicate.label ='allow')时,第二轮分析未完成。 I expect this is due to Knitr relabeling the chunk to Analysis-1, which is not specified in the R script. 我希望这是由于Knitr将块重标记为Analysis-1所致,R脚本中未指定该块。

I have also tried to run the scripts through a child-Rmd file, but this did not work either. 我也尝试通过子Rmd文件运行脚本,但这也不起作用。

Can anyone help here? 有人可以帮忙吗?

I think that source should work for you 我认为该source应该为您工作

Consider that I have a file called test.R 考虑我有一个名为test.R的文件

x <- a + b
print(x)

Now, from my Rmarkdown, I will source test.R twice: 现在,从我的Rmarkdown中,我将两次test.R

---
title: "Untitled"
output: html_document
---


```{r}
a <- 1
b <- 2

source("test.R")
```

```{r}
a <- 3
b <- 4

source("test.R")
```

This gives me the result 这给我结果

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM