R Markdown: Importing R script objects

2019-08-25 08:30发布

问题:

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.

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) 

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

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?

回答1:

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)

  • 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

  • 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/

  • 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.

An example:

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