r - 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”两次的情况下实现这一点?
解决方案
这里是我的工作流程,而不是采购 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
```
推荐阅读
- c# - 如何连接到安装在 Linux 中的 RabbitMQ
- winapi - 如果DLL不存在,您将在启动时完成而不停止的DLL的加载时间绑定称为什么
- unity3d - Unity PhotoCapture 返回“没有可用的捕获设备。” Hololens2 上的错误
- asp.net - 使用 Docker 本地开发刷新 Asp.Net 应用程序中的更改
- google-cloud-platform - 已执行阈值,但在 StackDiver 中未创建任何事件
- css - ElementUI:el-table__固定高度变化
- android - 在没有 Android SDK 的情况下在 Jenkins 上生成 APK
- java - CheckMarx - 如何修复代码注入报告?
- forms - 防止清除按钮擦除隐藏字段
- wordpress - ACF get_field_object() 只返回第一个对象,然后返回 NULL