简体   繁体   English

使用Knitr编译.Rmd文件时在第二个文件中调用函数

[英]Calling functions in a second file when compiling .Rmd files with knitr

I want to use knitr to format an R markdown file, lets call it Main.rmd . 我想使用knitr格式化R markdown文件,将其Main.rmd Some code in Main.rmd relies on helper functions in a second file, lets call it Functions.rmd . Main.rmd某些代码依赖于第二个文件中的辅助函数,可以将其称为Functions.rmd When I first run Functions.rmd and then Main.rmd , the code in Main.rmd runs fine. 当我第一次运行Functions.rmd然后Main.rmd ,在代码Main.rmd运行正常。 When I first run Functions.rmd and then try to knit Main.rmd , I receive an evaluation: 当我第一次运行Functions.rmd ,然后尝试编织Main.rmd ,我收到一个评估:

Error "Object 'myfunction' not found 错误“找不到对象'myfunction'

How can I fix this without combining Main.rmd and Functions.rmd into a single document, which I would like to avoid doing? 我如何避免在不将Main.rmdFunctions.rmd合并到一个文档中的情况下解决此问题?

Edit: I've added a toy example below. 编辑:我在下面添加了一个玩具示例。 There are very useful suggestions so far for how to call the functions in Functions.rmd from Main.rmd , but they all require converting Functions.rmd to a .R file. 到目前为止,关于如何从Main.rmd调用Functions.rmd的函数,有非常有用的建议,但是它们都需要将Functions.rmd转换为.R文件。 However, for my current purpose, it is important that Functions.rmd can also be read as a standalone markdown document. 但是,就我当前的目的而言, Functions.rmd也可以作为独立的markdown文档阅读,这一点很重要。

First, Main.rmd : 首先, Main.rmd

---
title: "Main_test"
author: "Matt Nolan"
date: "25/06/2018"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Background.
This is the main body of text and code used to display results of analyses, some of which are created by calling functions in Functions.Rmd.

```{r cars}
myexamplefunction(1,2)
```

And, here is Functions.rmd : 并且,这里是Functions.rmd

---
title: "Functions_test"
author: "Matt Nolan"
date: "25/06/2018"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Background
This is a document containing functions used in the document "Main_test". 
Because it contains functions and formatted text to explain the functions for an interested reader, it should be usable as a standalone markdown document.

For example, this is a function that adds two numbers.
```{r cars}
myexamplefunction <- function(a, b) {a + b}
```

30Jun2018 Update: R Markdown does not support combining Rmd files 2018年6月30日更新:R Markdown不支持合并Rmd文件

Matt's 25Jun2018 update clarifies the question, asking how to embed one Rmd document in another Rmd document. Matt的2018年6月25日更新澄清了这个问题,询问如何将一个Rmd文档嵌入另一个Rmd文档中。 Per the R Markdown website, R Markdown requires a single Rmd file. 根据R Markdown网站,R Markdown需要一个 Rmd文件。 It does not currently support the embedding of one Rmd file within another Rmd document. 它当前不支持将一个Rmd文件嵌入另一个Rmd文档中。

在此处输入图片说明

That said, with the bookdown package, you could structure the Rmd files as chapters in a book, where each Rmd file is a chapter in the book. 就是说,使用bookdown软件包,您可以将Rmd文件构造为书籍中的章节,其中每个Rmd文件都是书籍中的章节。 For details, see Bookdown: Authoring Books with R Markdown 1.4 - Two Rendering Approaches , the Getting Started page, and the Bookdown Demo github repository for an example book built in bookdown . 有关详细信息,请参阅Bookdown:有R降价创作书籍 1.4 -两个呈现途径 ,在入门页和Bookdown演示 GitHub的仓库建在一个例子书bookdown

25Jun2018 Update: Printing the code in an Appendix 2018年6月25日更新:在附录中打印代码

Per the comments from the OP, the reason for including the functions in an Rmd file instead of an R file was to obtain a formatted printout of the code in an Appendix. 根据OP的评论,将功能包含在Rmd文件而不是R文件中的原因是为了获取附录中代码的格式化打印输出。 This is possible with the technique I originally posted plus a few changes. 通过我最初发布的技术以及一些更改,这是可能的。

  1. Use named chunks to put the code in an appendix, and use the arguments echo=TRUE and eval=FALSE to avoid executing it multiple times. 使用命名块将代码放在附录中,并使用参数echo=TRUEeval=FALSE避免多次执行。
  2. Execute code from the Appendix in main flow of the document by way of the ref.label= argument, and keep the code from printing in the main document with the echo=FALSE argument. 通过ref.label=参数在文档主流程中执行附录中的代码,并使用echo=FALSE参数使代码不会在主文档中打印。
  3. In addition to using the source() function, one must print each function in another chunk in the appendix in order to obtain formatted print of each function. 除了使用source()函数外,还必须在附录的另一块中打印每个函数,以获得每个函数的格式化打印。

An updated version of my example Rmd file is listed below. 下面列出了我的示例Rmd文件的更新版本。

---
title: "TestIncludedFiles"
author: "Len Greski"
date: "June 24, 2018"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Background

A question was posted on [Stackoverflow](https://stackoverflow.com/questions/51013924/calling-functions-in-a-second-file-when-compiling-rmd-files-with-knitr) about how to include functions from one Rmd file while knitting another. 

If the second file contains R functions to be accessed in the second Rmd file, they're best included as R files rather than Rmd. In this example we'll include three files of functions from the Johns Hopkins University *R Programming* course: `pollutantmean()`, `corr()`, and `complete()`. We'll execute them in a subsequent code block. 

After an update to the original post where the original poster noted that he included the functions in an Rmd file in order to provide a formatted printout of the code in the report as an appendix, I've modified this example to account for this additional requirement. 

```{r ref.label="sourceCode",echo=FALSE}
 # execute sourceCode chunk from appendix 
```

## Executing the sourced files

Now that the required R functions have been sourced, we'll execute them.


```{r runCode, echo=TRUE}
pollutantmean("specdata","nitrate",70:72)
complete("specdata",1:10)
corr("specdata",threshold=500)
```

# Appendix 


```{r sourceCode,echo=FALSE,eval=FALSE}
# use source() function to source the functions we want to execute
source("./rprogramming/oneLine_pollutantmean.r")
source("./rprogramming/oneLine_complete.r")
source("./rprogramming/oneLine_corr.r")
```

The following is an inventory of the functions used in this Rmd file.

```{r }
pollutantmean
complete
corr
```

...and the output for the Appendix section of the document (with redactions to avoid publishing answers to a class programming assignment). ...以及该文件附录部分的输出(为避免发布类编程任务的答案而进行了删节)。

在此处输入图片说明

Original Answer 原始答案

If the second Rmd file only contains functions, you're better off saving them as an R file and using source() to include them in Main.Rmd . 如果第二个Rmd文件仅包含函数,则最好将它们另存为R文件,并使用source()将它们包括在Main.Rmd For example: 例如:

date: "June 24, 2018"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

## Background

A question was posted on [Stackoverflow](https://stackoverflow.com/questions/51013924/calling-functions-in-a-second-file-when-compiling-rmd-files-with-knitr) about how to include functions from one Rmd file while knitting another. 

If the second file contains R functions to be accessed in the second Rmd file, they're best included as R files rather than Rmd. In this example we'll include three files of functions from the Johns Hopkins University *R Programming* course: `pollutantmean()`, `corr()`, and `complete()`. We'll execute them in a subsequent code block. 

```{r sourceCode,echo=TRUE}
# use source() function to source the functions we want to execute
source("./rprogramming/pollutantmean.r")
source("./rprogramming/complete.r")
source("./rprogramming/corr.r")
```

## Executing the sourced files

Now that the required R functions have been sourced, we'll execute them.


```{r runCode, echo=TRUE}
pollutantmean("specdata","nitrate",70:72)
complete("specdata",1:10)
corr("specdata",threshold=500)
```

...produces the following output: ...产生以下输出:

在此处输入图片说明

DISCLOSURE: This answer includes techniques that I previously posted as a blog article in 2016, ToothGrowth Assignment: Accessing R Code from an Appendix in Knitr . 披露:此答案包括我以前在2016年作为博客文章ToothGrowth Assignment:从Knitr中的附录访问R代码张贴的技术。

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

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