30Jun2018 Обновление: R Markdown не поддерживает объединение файлов Rmd
Обновление Matt 25Jun2018 проясняет вопрос, спрашивая, как встроить один документ Rmd в другой документ Rmd.Для веб-сайта R Markdown для R Markdown требуется один Rmd-файл.В настоящее время он не поддерживает встраивание одного файла Rmd в другой документ Rmd.
![enter image description here](https://i.stack.imgur.com/bZBKI.png)
Тем не менее, с помощью пакета bookdown
вы можете структурировать файлы Rmd как главы в книге, где каждый файл Rmd является главойв книге.Для получения дополнительной информации см. Bookdown: создание книг с уценкой R 1.4 - два подхода к визуализации , страница Getting Started и Bookdown Demo репозиторий github для примера книги, встроенной в bookdown
.
25июнь2018 Обновление: печать кода в приложении
Согласно комментариям от OP, причиной включения функций в файл Rmd вместо файла R было получение отформатированной распечаткикод в приложении.Это возможно с техникой, которую я первоначально опубликовал, плюс несколько изменений.
- Используйте именованные чанки, чтобы поместить код в приложение, и используйте аргументы
echo=TRUE
и eval=FALSE
, чтобы избежать его многократного выполненияраз. - Выполнить код из Приложения в основном потоке документа с помощью аргумента
ref.label=
и сохранить код от печати в основном документе с аргументом echo=FALSE
. - 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](https://i.stack.imgur.com/jUv21.png)
Оригинальный ответ
Если второй 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](https://i.stack.imgur.com/dhRfU.png)
РАСКРЫТИЕ: Этоответ включает в себя методы, которые я ранее опубликовал в виде статьи в блоге в 2016 году, Назначение зуба: доступ к R-коду из приложения в Knitr .