我一直在阅读关于R Markdown(这里,这里,这里)并使用它来创建可靠的报告.我想尝试使用我正在运行的小代码进行一些临时分析,并将它们转换为更具伸缩性的数据报告.
我的问题相当广泛:是否有适当的方法来围绕R Markdown项目组织代码?比方说,有一个生成所有数据结构的脚本?
例如:假设我有cars数据集,并且我已经在制造商处引入了商业数据.如果我想将制造商附加到当前cars数据集,然后使用操纵数据集为每个公司生成单独的汇总表cars.by.name以及使用某个样本绘制图表,该cars.import怎么办?
编辑:现在我打开了两个文件.一个是具有所有数据操作的R脚本文件:子集化和重新分类值.另一个是R Markdown文件,我正在构建文本以配合各种感兴趣的表格和图表.当我从R脚本文件中调用一个对象时 - 比如:
```{r}
table(cars.by.name$make)
```
Run Code Online (Sandbox Code Playgroud)
我收到一个错误说 Error in summary(cars.by.name$make) : object 'cars.by.name' not found
编辑2:我发现这个较旧的帖子很有帮助.链接
---
title: "Untitled"
author: "Jeb"
date: "August 4, 2015"
output: html_document
---
This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see <http://rmarkdown.rstudio.com>.
When you click the **Knit** button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
```{r}
table(cars.by.name$make)
```
```{r}
summary(cars)
summary(cars.by.name)
```
```{r}
table(cars.by.name)
```
You can also embed plots, for example:
```{r, echo=FALSE}
plot(cars)
plot(cars.import)
```
Note that the `echo = FALSE` parameter was added to the code chunk to prevent printing of the R code that generated the plot.
Run Code Online (Sandbox Code Playgroud)
没有为这类问题的解决方案,解释在这里.
基本上,如果您有一个包含代码的.R文件,则无需重复.Rmd文件中的代码,但您可以包含.R文件中的代码.为此,代码块应在.R文件中命名,然后可以在.Rmd文件中按名称包含.
## ---- chunk-1 ----
table(cars.by.name$make)
Run Code Online (Sandbox Code Playgroud)
只有一次在.Rmd文件之上:
```{r echo=FALSE, cache= F}
knitr::read_chunk('test.R')
```
Run Code Online (Sandbox Code Playgroud)
对于您所包含的每个块(替换chunk-1为.R文件中特定块的标签):
```{r chunk-1}
```
Run Code Online (Sandbox Code Playgroud)
请注意,它应该保留为空(按原样),在运行时,来自.R的代码将被带到此处并运行.
很多时候,我有很多报告需要运行相同的代码,但参数略有不同。单独调用我的所有“统计”函数,生成结果,然后仅引用是我通常所做的。方法如下:
---
title: "Untitled"
author: "Author"
date: "August 4, 2015"
output: html_document
---
```{r, echo=FALSE, message=FALSE}
directoryPath <- "rawPath" ##Something like /Users/userid/RDataFile
fullPath <- file.path(directoryPath,"myROutputFile.RData")
load(fullPath)
```
Some Text, headers whatever
```{r}
summary(myStructure$value1) #Where myStructure was saved to the .RData file
```
Run Code Online (Sandbox Code Playgroud)
您可以使用该save.image()命令保存 RData 文件。
希望有帮助!