首页 > 解决方案 > R Markdown:导入 R 脚本对象

问题描述

我有一个 R 代码,它可以从我的数据中生成多个图表和表格。我想在 Rmarkdown 中写一份报告,我想在其中只包含图表和表格而不重写 R 代码。一种方法是使用“read_chunk”功能,但它不符合我的目的。以下是我需要的一个简单示例。

假设我有以下 R 脚本“Example.r”

x <- 1:4
y <- sin(x)

####----Table
table  <- cbind(x,y)
####----Plot
plot_1 <- plot(x,y) 

现在在我的 R markdown 文件中,我想要以下内容:

```{r echo=FALSE, cache=FALSE}
knitr::read_chunk('Example.r')
``` 
The following table shows the results:
```{r Table, echo=FALSE}
```
One can depict the result in a plot as well:
```{r Plot, echo=FALSE}
```

在上面的示例中,我将无法插入表格或绘图,因为两者都需要在表格和绘图命令运行之前定义输入“x”和“y”。有没有办法在不硬编码“x”和“y”两次的情况下实现这一点?

标签: rr-markdown

解决方案


这里是我的工作流程,而不是采购 R 脚本,这可能对您有用:(对不起,我觉得它应该是一个评论,但它有点冗长)

  • 并排保存一个draft.rmd 和一个report.rmd。Draft.rmd 将成为您的工作场所,可进行探索性数据分析。并且report.rmd 将是您完善的报告

  • 收集要放入报表的列表中的结果(如 data.frames 和 ggplot 对象)。将列表保存为result_181023.rda文件。在像这样的文件夹中data/

  • 将保存的result_181023.rda文件加载到report.rmd 中,绘制图表并打印表格并按照您喜欢的方式润色您的报告。

一个例子:

```{r data echo=FALSE, cache=FALSE}
# a list named result.list
# With a table result.list$df 
# and a ggplot object: result.list$gg1
load("data/result_181023.rda")

``` 

The following table shows the results:

```{r Table, echo=FALSE}
knitr::kable(result.list$df)
```

One can depict the result in a plot as well:
```{r Plot, echo=FALSE}
result.list$gg1
```

推荐阅读