Rmarkdown中的循环:如何制作文字参考?配图? [英] Loops in Rmarkdown: How to make an in-text figure reference? Figure captions?

查看:145
本文介绍了Rmarkdown中的循环:如何制作文字参考?配图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{r setup, include=FALSE, message=FALSE, results="hide"} knitr::opts_chunk$set(echo = TRUE) library(knitr) library(kfigr) library(dplyr) library(png) library(grid) library(pander) library(ggplot2)

{r setup, include=FALSE, message=FALSE, results="hide"} knitr::opts_chunk$set(echo = TRUE) library(knitr) library(kfigr) library(dplyr) library(png) library(grid) library(pander) library(ggplot2)

rmarkdown中的循环:文本图形参考?人物字幕?

Loops in rmarkdown: in-text figure reference? figure captions?

使用for循环在图形列表中创建带有文本,文本结果以及带有图形标题的多个图形引用的节.在这些新章节之前和之后的附图编号中,附图引用/编号应该没有太大的意义.

Use a for loop to create sections with text, in-text results, and multiple figure references with associated figure captions in the figure list. The figure references/numbering should be seemless with figures numbered before and after these new sections.

注意: for循环中引用的图形是在文本的前面生成的,另存为png,然后重新加载.就本例而言,这似乎有些笨拙,但实际的无花果是地图,生成起来很慢(我打算注释掉想要的数字后再生成它们的循环).

Note: The figures referenced in the for loop are generated earlier in the text, saved as pngs, and then re-loaded. This might seem clunky for the purpose of this example, but the actual figs are maps and are slow to generate (I plan to comment out the loop that generates the figures once I have them how I want).

{r echo = FALSE, warnings=FALSE, message=FALSE, results="hide"}

数据:每年我们的层数不同,因此需要循环.

df <- rbind(
  data.frame(strata = rep("A", 10), x = rnorm(10, mean= 10), y = rnorm(10, mean = 15),z = rnorm(10, mean = 20)),
  data.frame(strata = rep("B", 10), x = rnorm(10, mean= 5), y = rnorm(10, mean = 10), z = rnorm(10, mean = 15)),
  data.frame(strata = rep("C", 10), x = rnorm(10, mean= 15), y = rnorm(10, mean = 20), z = rnorm(10, mean = 10)))

first_plot:在for循环之前应出现在列表中的图形将按层创建各个部分

first_plot <- ggplot(df, aes(x, fill=strata)) + geom_histogram()

last_plot:for循环创建按层创建的节后应出现在列表中的图形

last_plot <- ggplot(df, aes(x = strata, y = z)) + geom_boxplot()

图形生成(这是在我有自己想要的地图后将在以后的版本中注释掉的部分)

strat <- unique(df$strata)

for (i in seq_along(strat)) {
  sub <- df %>% filter(strata %in% strat[i])
  fig1 <- ggplot(sub, aes(x = x, y = y)) + geom_point()
  ggsave(fig1, file=paste0("fig1_", strat[i], ".png"))
  fig2 <- ggplot(sub, aes(x = x, y = z)) + geom_point() 
  ggsave(fig2, file=paste0("fig2_", strat[i], ".png"))
}    

加载png

df_figs <- list.files(pattern = "\\.png$")
for (i in df_figs){  
   name <- gsub("-",".",i)
   name <- gsub(".png","",name)  
   i <- paste(".\\",i,sep="")
   assign(name,readPNG(i))
}

简介部分

报告中的一些介绍性文字和数字r figr('first_plot',TRUE, type='Figure').

```{r echo = FALSE, warnings=FALSE, message=FALSE, results = "asis"}

# Summary of results and image file names that will be references in text
results <- df %>% 
  group_by(strata) %>% 
  dplyr::summarise_each(funs(mean)) %>% 
  mutate(fig1 = paste0("fig1_", strata),
         fig2 = paste0("fig2_", strata))

#Text template (each strata will have its own section)
template <- "# The %s stratum
The mean of *x* in %s stratum was %1.1f. Relationships between *x* and *y* and *x* and *z* can be found in `r figr('%s', TRUE, type='Figure')` and `r figr('%s', TRUE, type='Figure')`.

"

#Create markdown sections in for loop
for(i in seq(nrow(results))) {
  current <- results[i, ]
  cat(sprintf(template, 
              current$strata, current$strata, 
              current$x, 
              current$fig1, current$fig2))
}

#Also doesn't work:
template <- "# The %s stratum
The mean in %s stratum was %1.0f. Results can be found in "
template2 <- " and "
template3 <- ".

"

`figr('%s', TRUE, type='Figure')` and `figr('%s', TRUE, type='Figure')`."

#For loop
for(i in seq(nrow(results))) {
  current <- results[i, ]
  cat(sprintf(template,
            current$strata, current$strata,
            current$mean,
            current$fig_1, current$fig_2))
  print(paste0("`r figr(",paste0("'", current$fig1,"'"), TRUE, type='Figure'))
  cat(sprintf(template2))
  print(paste0("`r figr(",paste0("'", current$fig2,"'"), "TRUE, type='Figure'),`"))
  cat(sprintf(template3))
 }
```

结论部分

报告中的一些讨论文字和图r figr('last_plot',TRUE, type='Figure').

*NOTE:* I don't know how to automate the looped portion of the list of figures here, so I've done it by hand.

```{r 'first_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="The caption for the first figure."}
suppressMessages(print(first_plot))
```

```{r 'fig1_A', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig1_A."}
grid.raster(fig1_A)
```

```{r 'fig2_A', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig2_A."}
grid.raster(fig2_A)
```

```{r 'fig1_B', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig1_B."}
grid.raster(fig1_B)
```

```{r 'fig2_B', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig2_B."}
grid.raster(fig2_B)
```

```{r 'fig1_C', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig1_C."}
grid.raster(fig1_C)
```

```{r 'fig2_C', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="Caption text for fig2_C."}
grid.raster(fig2_C)
```

```{r 'last_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6,  fig.cap="The caption for the last figure."}
suppressMessages(print(last_plot))
```

推荐答案

解决方案

  1. 使用knit_expand()
  2. 使用captioner代替kfigr
  3. 这会在文本中和报告末尾为您的数字(或表格)编号.
  4. 此脚本显示了如何在for循环中创建带有文本引用的图形的markdown段落.
  5. 它还向您展示了如何在for循环中创建自定义图形标题,同时保留数字顺序.
  6. 如果您演示如何使用brew执行#4和#5,我将为您提供所有SO点.
  1. Use knit_expand()
  2. Use captioner instead of kfigr
  3. This numbers your figures (or tables) in text and at the end of your report.
  4. This script shows you how to create markdown paragraphs in for loops that have in-text references to figures.
  5. It also shows you how to create custom figure captions in for loops while retaining the number order.
  6. If you show how to do #4 and #5 using brew I will give you all the SO points.

图书馆

library(knitr) library(dplyr) library(png) library(grid) library(pander) library(ggplot2) library(devtools) library(captioner)

Libraries

library(knitr) library(dplyr) library(png) library(grid) library(pander) library(ggplot2) library(devtools) library(captioner)

使用captioner包创建fig_nums()函数 ( https://github.com/adletaw/captioner/blob/master /vignettes/using_captioner.Rmd )

fig_nums <- captioner(prefix = "Figure")

数据

每年我们的层数不同,因此需要循环.

df <- rbind(
  data.frame(strata = rep("A", 10), x = rnorm(10, mean= 10), y = rnorm(10, mean = 15), z = rnorm(10, mean = 20)),
  data.frame(strata = rep("B", 10), x = rnorm(10, mean= 5), y = rnorm(10, mean = 10), z = rnorm(10, mean = 15)),
  data.frame(strata = rep("C", 10), x = rnorm(10, mean= 15), y = rnorm(10, mean = 20), z = rnorm(10, mean = 10)))

first_plot:for循环之前应出现在列表中的图按层创建各节

first_plot: the figure that should appear in the list before for loop creates the sections by strata

first_plot <- ggplot(df, aes(x, fill=strata)) + geom_histogram()
fig_nums("first_plot", display = FALSE)

last_plot:for循环按层创建节后应出现在列表中的图形

last_plot: the figure that should appear in the list after the for loop creates the sections by strata

last_plot <- ggplot(df, aes(x = strata, y = z)) + geom_boxplot()

图形生成

了解无花果后,请注释掉此部分.如果您在R中进行了大量映射,则此步骤不会感到费解,不自然,次优,不必要,也不会像一个非常糟糕的主意.

strat <- unique(df$strata)

  for (i in seq_along(strat)) {
   sub <- df %>% filter(strata %in% strat[i])
   fig1 <- ggplot(sub, aes(x = x, y = y)) + geom_point()
   ggsave(fig1, file=paste0("fig1_", strat[i], ".png"))
   fig2 <- ggplot(sub, aes(x = x, y = z)) + geom_point() 
   ggsave(fig2, file=paste0("fig2_", strat[i], ".png"))
 }        

加载png

df_figs <- list.files(pattern = "\\.png$")
for (i in df_figs){  
   name <- gsub("-",".",i)
   name <- gsub(".png","",name)  
   i <- paste(".\\",i,sep="")
   assign(name,readPNG(i))
}

简介

报告中的一些介绍性文字和数字r fig_nums("first_plot", display="cite").

将在文本中引用的结果和图像文件名:

Results and image file names that will be referenced in text:

```{r echo = FALSE, warnings=FALSE, message=FALSE, results = "asis"}

    results <- df %>% 
      group_by(strata) %>% 
      dplyr::summarise_each(funs(mean)) %>% 
      mutate(fig1 = paste0("fig1_", strata),
             fig2 = paste0("fig2_", strata))

```

```{r run-numeric-md, warning=FALSE, include=FALSE}

#The text for the markdown sections in for loop... the knit_expand() is the work-horse here.

out = NULL
for (i in as.character(unique(results$strata))) {
  out = c(out, knit_expand(text=c('#### The *{{i}}* strata',
                                  '\n',
                                  'The mean of *x* is ',
                                  '{{paste(sprintf("%1.1f", results$x[results$strata==i]))}}', '({{fig_nums(results$fig1[results$strata==i],display="cite")}}).',
                                  '\n'
  )))
}

```

为每个阶层创建一个部分

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

结论

报告中的一些讨论文字和图r fig_nums("last_plot",display="cite").

`r fig_nums("first_plot",caption="Here is the caption for the first figure.")`

```{r 'first_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6}
suppressMessages(print(first_plot))
```

```{r figcaps, include=FALSE}
caps = NULL

for (i in as.character(unique(results$strata))) {
  caps = c(caps, knit_expand(  
    text=c({{fig_nums(results$fig1[results$strata==i], caption="Caption text for strata *{{i}}* goes here.")}},
           '``` {r {{results$fig1[results$strata==i]}}, echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6}',
           {{paste0('grid.raster(',results$fig1[results$strata==i],')')}},
                                    '```',
           '\n')))
}

#DON'T FORGET TO UNLIST!
src <- unlist(caps)
```

`r paste(knit(text = src),sep='\n')`

`r fig_nums("last_plot", caption="The caption for the last figure.")`

```{r 'last_plot', echo=FALSE, warning=FALSE, fig.width=6.5, fig.height=6}
suppressMessages(print(last_plot))
```

这篇关于Rmarkdown中的循环:如何制作文字参考?配图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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