已经有一些关于此的问题,但它们要么不清楚,要么提供了不起作用的解决方案,可能是因为它们已经过时了:
大型项目的模块化代码结构
R Markdown/Notebook 很好,但它的呈现方式通常只有一个文件,其中包含所有文本和所有代码块。我经常有这样的单个文件结构不是一个好的设置的项目。相反,我使用单个
.R
加载另一个 .R
的主文件文件顺序。我想使用 R Notebook 复制这个结构,即我有一个 .Rmd
我从多个 .R
调用代码的文件文件来自。以这种方式处理项目的好处是它允许使用
.R
与 RStudio 进行正常的工作流程。文件,还有 R Notebook/Markdown 的简洁输出,无需复制代码。最小的例子
这被简化以使示例尽可能小。两个
.R
文件和一个主 .Rmd
文件。start.R
# libs --------------------------------------------------------------------
library(pacman)
p_load(dplyr, ggplot2)
#normally load a lot of packages here
# data --------------------------------------------------------------------
d = iris
#use iris for example, but normally would load data from file
# data manipulation tasks -------------------------------------------------
#some code here to extract useful info from the data
setosa = dplyr::filter(d, Species == "setosa")
plot.R
#setosa only
ggplot(setosa, aes(Sepal.Length)) +
geom_density()
#all together
ggplot(d, aes(Sepal.Length, color = Species)) +
geom_density()
然后是笔记本文件:
notebook.Rmd
:---
title: "R Notebook"
output:
html_document: default
html_notebook: default
---
First we load some packages and data and do slight transformation:
```{r start}
#a command here to load the code from start.R and display it
```
```{r plot}
#a command here to load the code from plot.R and display it
```
期望的输出
所需的输出是从
start.R
手动复制代码得到的。和 plot.R
进入 notebook.Rmd
中的代码块.这看起来像这样(由于屏幕空间不足而丢失了一些):我尝试过的事情
source
这会加载代码,但不会显示它。它只显示
source
命令:knitr::read_chunk
提到了这个命令here , 但实际上它与
source
的作用相同据我所知:它加载代码但不显示任何内容。如何获得所需的输出?
最佳答案
解决方法是使用 knitr 的 block 选项 code
.根据knitr docs :
code: (NULL; character) if provided, it will override the code in the current chunk; this allows us to programmatically insert code into the current chunk; e.g. a chunk option code = capture.output(dump('fivenum', '')) will use the source code of the function fivenum to replace the current chunk
然而,没有提供示例。听起来必须给它一个字符向量,所以让我们试试
readLines
:```{r start, code=readLines("start.R")}
```
```{r plot, code=readLines("start.R")}
```
这会产生所需的输出,从而允许模块化的项目结构。
直接向它提供文件不起作用(即
code="start.R"
),但会是一个很好的增强。
关于r - 模块化的 R markdown 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40519904/