R Markdown:导入 R 脚本对象 [英] R Markdown: Importing R script objects

查看:99
本文介绍了R Markdown:导入 R 脚本对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an R code that generates several plots and tables from my data. I want to write a report in Rmarkdown in which i want to include just the plots and the tables without rewriting the R code. One way is to use 'read_chunk' function but it does not serve my purpose. Following is a simple example of what i need.

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

Suppose I have the following R script 'Example.r'

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

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

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

Now in my R markdown file i want the following:

```{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' 的情况下实现它?

In the above example, i will not be able to insert either the table or the plot, since both need the input 'x' and 'y' to be defined before the table and the plot commands are run. Is there a way to implement this without hardcoding 'x' and 'y' two times?

推荐答案

这里不是获取 R 脚本,而是我的工作流程,它可能对您有用:(抱歉,我觉得应该是评论,但有点冗长)

Instead of sourcing an R script, here is my workflow which might be useful to you: (sorry I feel it should be a comment but it gets a bit lengthy)

  • 并排保存一个draft.rmd 和一个report.rmd.该 Draft.rmd 将是您的工作场所,具有探索性数据分析.并且 report.rmd 将成为您的精美报告

  • Keep a draft.rmd and a report.rmd side by side. the draft.rmd will be your workplace with exploratory data analysis. and the report.rmd will be your polished report

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

Gather results (like data.frames & ggplot objects) you want to put in the report in a list. Save the list as a result_181023.rda file. in a folder like data/

在report.rmd中加载保存的result_181023.rda文件,绘制你的图形&按您喜欢的方式打印表格并润色报告.

Load the saved result_181023.rda file in the report.rmd, draw your figures & print your tables and polish your report the way you like.

示例:

```{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
```

这篇关于R Markdown:导入 R 脚本对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆