Вызов функций во втором файле при компиляции файлов .Rmd с помощью knitr - PullRequest
0 голосов
/ 25 июня 2018

Я хочу использовать knitr для форматирования файла уценки R, давайте назовем его Main.rmd. Некоторый код в Main.rmd опирается на вспомогательные функции во втором файле, давайте назовем его Functions.rmd. Когда я впервые запускаю Functions.rmd, а затем Main.rmd, код в Main.rmd работает нормально. Когда я впервые запускаю Functions.rmd, а затем пытаюсь связать Main.rmd, я получаю оценку:

Ошибка "Объект 'myfunction' не найден

Как я могу исправить это, не объединяя Main.rmd и Functions.rmd в один документ, чего я бы хотел избежать?

Редактировать: я добавил игрушечный пример ниже. Пока есть очень полезные предложения о том, как вызывать функции в Functions.rmd из Main.rmd, но все они требуют преобразования Functions.rmd в файл .R. Однако для моей текущей цели важно, чтобы Functions.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)
```

А вот 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}
```

1 Ответ

0 голосов
/ 25 июня 2018

30Jun2018 Обновление: R Markdown не поддерживает объединение файлов Rmd

Обновление Matt 25Jun2018 проясняет вопрос, спрашивая, как встроить один документ Rmd в другой документ Rmd.Для веб-сайта R Markdown для R Markdown требуется один Rmd-файл.В настоящее время он не поддерживает встраивание одного файла Rmd в другой документ Rmd.

enter image description here

Тем не менее, с помощью пакета bookdown вы можете структурировать файлы Rmd как главы в книге, где каждый файл Rmd является главойв книге.Для получения дополнительной информации см. Bookdown: создание книг с уценкой R 1.4 - два подхода к визуализации , страница Getting Started и Bookdown Demo репозиторий github для примера книги, встроенной в bookdown.

25июнь2018 Обновление: печать кода в приложении

Согласно комментариям от OP, причиной включения функций в файл Rmd вместо файла R было получение отформатированной распечаткикод в приложении.Это возможно с техникой, которую я первоначально опубликовал, плюс несколько изменений.

  1. Используйте именованные чанки, чтобы поместить код в приложение, и используйте аргументы echo=TRUE и eval=FALSE, чтобы избежать его многократного выполненияраз.
  2. Выполнить код из Приложения в основном потоке документа с помощью аргумента ref.label= и сохранить код от печати в основном документе с аргументом echo=FALSE.
  3. InПомимо использования функции source(), необходимо распечатать каждую функцию в другом фрагменте в приложении, чтобы получить форматированную печать каждой функции.

Обновленная версия моего примера файла 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](/9895669/vyzov-funktsii-vo-vtorom-faile-pri-kompilyatsii-failov-rmd-s-pomoschy-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
```

... и вывод для раздела Приложения в документе (с изменениями, чтобы избежать публикации ответов на задание по программированию класса).

enter image description here

Оригинальный ответ

Если второй Rmd-файл содержит только функции, лучше сохранить их как R-файл ииспользуя source(), чтобы включить их в Main.Rmd.Например:

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

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

## Background

A question was posted on [Stackoverflow](/9895669/vyzov-funktsii-vo-vtorom-faile-pri-kompilyatsii-failov-rmd-s-pomoschy-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)
```

... производит следующий вывод:

enter image description here

РАСКРЫТИЕ: Этоответ включает в себя методы, которые я ранее опубликовал в виде статьи в блоге в 2016 году, Назначение зуба: доступ к R-коду из приложения в Knitr .

...