R knitr Markdown:For循环内的输出图 [英] R knitr Markdown: Output Plots within For Loop
问题描述
我想创建一个自动化的knitr报告,为我的数据框中的每个数字字段生成直方图。我的目标是在不必指定实际字段的情况下执行此操作(此数据集包含超过70个字符,我还想重用该脚本)。
我尝试了几种不同的方法:
p
,然后在循环之后调用 p
PLOTS < - NULL
PLOTS< - append(PLOTS,p)
.png
文件,但宁可不必处理保存和然后重新访问每个文件的开销
我恐怕这些情节设备的错综复杂都在逃避我。
问题
如何将以下块输出到报表的循环中?目前,我能达到的最好效果是通过将其保存到一个对象并在循环外部调用该对象所产生的最终打印输出。
使用<$在RStudio中,c $ c> knitr :
```{plotNumeric,echo = TRUE,
suppressPackageStartupMessages(library(ggplot2))
FIELDS < - names(df)[sapply(df,class)==numeric]
for(field in FIELDS){
qplot(df [,field],main = field)
}
```
从这一点来看,我希望能够进一步定制这些情节。 print 。
knitr
会为您做到这一点,如果 qplot
是在一个循环之外,但是(至少是我已经安装的版本)在循环内部没有检测到它(这与R命令行的行为一致)。
I would like to create an automated knitr report that will produce histograms for each numeric field within my dataframe. My goal is to do this without having to specify the actual fields (this dataset contains over 70 and I would also like to reuse the script).
I've tried a few different approaches:
- saving the plot to an object,
p
, and then callingp
after the loop- This only plots the final plot
- Creating an array of plots,
PLOTS <- NULL
, and appending the plots within the loopPLOTS <- append(PLOTS, p)
- Accessing these plots out of the loop did not work at all
- Even tried saving each to a
.png
file but would rather not have to deal with the overhead of saving and then re-accessing each file
I'm afraid the intricacies of the plot devices are escaping me.
Question
How can I make the following chunk output each plot within the loop to the report? Currently, the best I can achieve is output of the final plot produced by saving it to an object and calling that object outside of the loop.
R markdown chunk using knitr
in RStudio:
```{r plotNumeric, echo=TRUE, fig.height=3}
suppressPackageStartupMessages(library(ggplot2))
FIELDS <- names(df)[sapply(df, class)=="numeric"]
for (field in FIELDS){
qplot(df[,field], main=field)
}
```
From this point, I hope to customize the plots further.
Wrap the qplot
in print
.
knitr
will do that for you if the qplot
is outside a loop, but (at least the version I have installed) doesn't detect this inside the loop (which is consistent with the behaviour of the R command line).
这篇关于R knitr Markdown:For循环内的输出图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!