模块化R降价结构

时间:2016-11-10 04:19:33

标签: r r-markdown rnotebook

有一些问题已经存在,但它们要么不清楚,要么提供不起作用的解决方案,可能是因为它们已经过时了:

大型项目的模块化代码结构

Markdown /笔记本很不错,但就其呈现方式而言,通常只有一个文件包含所有文本和所有代码块。我经常有一些项目,这样的单一文件结构不是一个好的设置。相反,我使用单个.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.Rplot.R的代码手动复制到notebook.Rmd中的代码块中的输出。这看起来像这样(由于缺少屏幕空间而丢失了一些):

enter image description here

我尝试过的事情

source

这会加载代码,但不会显示它。它只显示source命令:

enter image description here

knitr::read_chunk

这个命令被提到here,但实际上它与source的作用相同:据我所知:它加载代码但没有显示任何内容。

enter image description here

如何获得所需的输出?

3 个答案:

答案 0 :(得分:4)

解决方案是使用knitr的块选项code。根据{{​​3}}:

  

代码:( NULL;字符)如果提供,它将覆盖中的代码   目前的块;这允许我们以编程方式将代码插入到   目前的块;例如块选项代码=   capture.output(dump('fivenum',''))将使用的源代码   函数fivenum替换当前的块

但是没有提供示例。听起来像是要为它提供一个字符向量,所以让我们试试readLines

```{r start, code=readLines("start.R")}
```

```{r plot, code=readLines("start.R")}
```

这会产生所需的输出,从而允许模块化的项目结构。

直接向它提供文件不起作用(即code="start.R"),但这将是一个很好的增强。

答案 1 :(得分:2)

为了与R笔记本电脑互操作,您可以使用如上所述的knitr read_chunk方法。在笔记本中,您必须在设置块中调用read_chunk;因为您可以按任何顺序运行笔记本块,这可以确保外部代码始终可用。

以下是使用read_chunk将外部R脚本中的代码导入笔记本的最小示例:

<强> example.Rmd

```{r setup}
knitr::read_chunk("example.R")
```

```{r chunk}
```

<强> example.R

## ---- chunk
1 + 1

当您在笔记本中执行空块时,将插入外部文件中的代码,并且结果以内联方式显示,就好像块包含该代码一样。

Notebook Output

答案 2 :(得分:1)

根据我上面的评论,我使用这里的库来处理文件夹中的项目:

 ```{ r setup, echo=FALSE, message=FALSE, warning=FALSE, results='asis'}

library(here) 

insert <- function(filename){
  readLines(here::here("massive_report_folder", filename))
}
```

然后每个块看起来像

```{ r setup, echo=FALSE, message=FALSE, warning=FALSE, 
        results='asis', code=insert("extra_file.R")}
```
相关问题