【问题标题】:R markdown: Use for loop to generate text and display figure/tableR markdown:使用for循环生成文本并显示图形/表格
【发布时间】:2021-12-24 08:32:03
【问题描述】:

我认为 R markdown 可以使用 for 循环生成文本部分,请参阅this post。但是,我想知道是否也有可能生成图形和表格。

所以我做了一个简单的例子。假设在 R markdown 中,我想要 markdown 语言并在下面显示表格和绘图。

这将返回一个表格和一个绘图。

df<- data.frame(
  name = LETTERS[1:12],
  data = runif(n = 12))
new_df<-some_function(df,1)
formattable(new_df)
plot(new_df$data)

some_function 是一个简单的函数,它执行以下操作

some_function<-function(df,loc){
  df$data<-df$data+loc
  return(df)
}

所以我希望这个重复 5 次,这意味着生成下面的选择 5 次。

这将返回一个表格和一个绘图。

(图:假装那里显示了一个图) (table: 假装那里展示了一张桌子)

我应该如何使用一些模板编写代码来显示表格和数字?生成new_df列表的代码如下。

df_list=list()
for (i in 1:5){
  new_df<-some_function(df,i)
  df_list[[i]]<-new_df
}

目标是在 5 个单独的部分下显示表格 formattable(df_list[[i]]) 和数字 plot(df_list[[i]]$data)。 (假设每个部分的文本内容都比我做的例子更有意义)像下面这个 screktch 的东西。

template <- "## This will return a table and a figure.
Table is: formattable(df_list[[i]])
Figure is: plot(df_list[[i]]$data)

"

for (i in 1:5) {
  current <- df_list[[i]]
  cat(sprintf(template, current,current$data))
}

有可能做到这一点吗?任何想法或想法都非常欢迎。

【问题讨论】:

    标签: r r-markdown knitr


    【解决方案1】:

    您可以在r chunk 中使用result = 'asis',并使用cat() 创建部分。

    ---
    title: "R Notebook"
    output:
      html_document
    ---
    
    ## Example
    
    ```{r, results='asis'}
    require(ggplot2)
    for(i in 1:5){
      cat("### Section ", i, "\n")
      
      df <- mtcars[sample(5),]
      tb <- knitr::kable(df, caption = paste0("Table",i))
      g1 <- ggplot2::ggplot(df, aes(x = mpg, y = disp, fill = gear)) +
        ggplot2::geom_point() +
        ggplot2::labs(title = paste0("Figure ", i))
      cat("\n")
      print(g1)
      print(tb)
      cat("\n")
    }
    ```
    

    【讨论】:

    • 感谢您解决我的问题,它似乎有效!
    猜你喜欢
    • 2019-03-11
    • 2021-04-17
    • 2013-06-15
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2016-04-16
    • 1970-01-01
    • 2020-03-16
    相关资源
    最近更新 更多