简体   繁体   English

R knitr Markdown:For循环内的输出图

[英]R knitr Markdown: Output Plots within For Loop

I would like to create an automated knitr report that will produce histograms for each numeric field within my dataframe.我想创建一个自动 knitr 报告,该报告将为我的数据框中的每个数字字段生成直方图。 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).我的目标是在不必指定实际字段的情况下执行此操作(此数据集包含 70 多个,我还想重用该脚本)。

I've tried a few different approaches:我尝试了几种不同的方法:

  • saving the plot to an object, p , and then calling p after the loop将绘图保存到对象p ,然后在循环后调用p
    • This only plots the final plot这仅绘制最终图
  • Creating an array of plots, PLOTS <- NULL , and appending the plots within the loop PLOTS <- append(PLOTS, p)创建一个绘图数组PLOTS <- NULL ,并将绘图附加到循环PLOTS <- 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甚至尝试将每个文件保存到.png文件,但宁愿不必处理保存然后重新访问每个文件的开销

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:在 RStudio 中使用knitr的 R 降价块:

```{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 .qplot包装在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).如果qplot在循环之外, knitr将为您执行此操作,但是(至少我安装的版本)在循环内没有检测到这一点(这与 R 命令行的行为一致)。

Wish to add a quick note: Somehow I googled the same question and get into this page.希望添加一个快速说明:不知何故,我用谷歌搜索了同样的问题并进入了这个页面。 Now in 2018, just use print() in the loop.现在在 2018 年,只需在循环中使用print()即可。

for (i in 1:n){
...
    f <- ggplot(.......)
    print(f)
}

I am using child Rmd files in markdown, also works in sweave.我在 markdown 中使用子 Rmd 文件,也适用于 sweave。

in Rmd use following snippet:在 Rmd 中使用以下代码段:

```{r run-numeric-md, include=FALSE}
out = NULL
for (i in c(1:num_vars)) {
  out = c(out, knit_child('da-numeric.Rmd'))
}
```

da-numeric.Rmd looks like: da-numeric.Rmd 看起来像:

Variabele `r num_var_names[i]`
------------------------------------

Missing :  `r sum(is.na(data[[num_var_names[i]]]))`  
Minimum value : `r min(na.omit(data[[num_var_names[i]]]))`  
Percentile 1 : `r quantile(na.omit(data[[num_var_names[i]]]),probs = seq(0, 1, 0.01))[2]`  
Percentile 99 : `r quantile(na.omit(data[[num_var_names[i]]]),probs = seq(0, 1, 0.01))[100]`  
Maximum value : `r max(na.omit(data[[num_var_names[i]]]))`  

```{r results='asis', comment="" }
warn_extreme_values=3
d1 = quantile(na.omit(data[[num_var_names[i]]]),probs = seq(0, 1, 0.01))[2] > warn_extreme_values*quantile(na.omit(data[[num_var_names[i]]]),probs = seq(0, 1, 0.01))[1]
d99 = quantile(na.omit(data[[num_var_names[i]]]),probs = seq(0, 1, 0.01))[101] > warn_extreme_values*quantile(na.omit(data[[num_var_names[i]]]),probs = seq(0, 1, 0.01))[100]
if(d1){cat('Warning : Suspect extreme values in left tail')}
if(d99){cat('Warning : Suspect extreme values in right tail')}
```

``` {r eval=TRUE,  fig.width=6, fig.height=2}
library(ggplot2)

v <- num_var_names[i]
hp <- ggplot(na.omit(data), aes_string(x=v)) + geom_histogram( colour="grey", fill="grey", binwidth=diff(range(na.omit(data[[v]]))/100))

hp + theme(axis.title.x = element_blank(),axis.text.x = element_text(size=10)) + theme(axis.title.y = element_blank(),axis.text.y = element_text(size=10))

```

see my datamineR package on github https://github.com/hugokoopmans/dataMineR在 github 上查看我的 datamineR 包https://github.com/hugokoopmans/dataMineR

As an addition to Hugo's excellent answer, I believe that in 2016 you need to include a print command as well :作为 Hugo 出色答案的补充,我相信在 2016 年您还需要包含一个print命令

```{r run-numeric-md, include=FALSE}
out = NULL
for (i in c(1:num_vars)) {
  out = c(out, knit_child('da-numeric.Rmd'))
}

`r paste(out, collapse = '\n')`
```

For knitting Rmd to HTML, I find it more convenient to have a list of figures.对于将 Rmd 编​​织成 HTML,我发现有一个数字列表更方便。 In this case I get the desirable output with results='hide' as follows:在这种情况下,我得到了results='hide'的理想输出,如下所示:

 --- title: "Make a list of figures and show it" output: html_document --- ```{r} suppressPackageStartupMessages({ library(ggplot2) library(dplyr) requireNamespace("scater") requireNamespace("SingleCellExperiment") }) ``` ```{r} plots <- function() { print("print") cat("cat") message("message") warning("warning") # These calls generate unwanted text scater::mockSCE(ngene = 77, ncells = 33) %>% scater::logNormCounts() %>% scater::runPCA() %>% SingleCellExperiment::reducedDim("PCA") %>% as.data.frame() %>% { list( f12 = ggplot(., aes(x = PC1, y = PC2)) + geom_point(), f22 = ggplot(., aes(x = PC2, y = PC3)) + geom_point() ) } } ``` ```{r, message=FALSE, warning=TRUE, results='hide'} plots() ```

Only the plots are shown and the warnings (which you can switch off, as well).仅显示绘图和警告(您也可以将其关闭)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM