R Markdown,循环输出测试结果

标签 r r-markdown

我正在寻找在 for 循环中生成并用标题结构化的测试结果的格式良好的 Markdown 输出。例如

df <- data.frame(x = rnorm(1000),
           y = rnorm(1000),
           z = rnorm(1000))

for (v in c("y","z")) {
  cat("##", v, " (model 0)\n")
  summary(lm(x~1, df))

  cat("##", v, " (model 1)\n")
  summary(lm(as.formula(paste0("x~1+",v)), df))
}

而输出应该是

y(模型 0)
Call:
lm(formula = x ~ 1, data = df)

Residuals:
    Min      1Q  Median      3Q     Max 
-3.8663 -0.6969 -0.0465  0.6998  3.1648 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.05267    0.03293    -1.6     0.11

Residual standard error: 1.041 on 999 degrees of freedom

y(模型 1)
Call:
lm(formula = as.formula(paste0("x~1+", v)), data = df)

Residuals:
    Min      1Q  Median      3Q     Max 
-3.8686 -0.6915 -0.0447  0.6921  3.1504 

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.05374    0.03297  -1.630    0.103
y           -0.02399    0.03189  -0.752    0.452

Residual standard error: 1.042 on 998 degrees of freedom
Multiple R-squared:  0.0005668, Adjusted R-squared:  -0.0004346 
F-statistic: 0.566 on 1 and 998 DF,  p-value: 0.452

z(模型 0)

等等...

有几个结果讨论了问题的部分内容,例如 herehere建议asis -tag 与 cat 结合使用-陈述。 This one包括标题。

最接近我的请求似乎是 this question从两年前开始。然而,尽管受到高度赞赏,但一些建议已被弃用,例如 asis_output或者我无法让它们在像 formattable 这样的一般条件下工作建议(例如使用 lm -输出)。我只是想知道 - 从那以后两年过去了 - 是否有一种现代方法可以促进我正在寻找的东西。

最佳答案

解决方案类型 1

你可以做一个 capture.output(cat(.))接近一些 lapply -循环。将输出发送到文件并使用 rmarkdown::render(.) .

这是产生 *.pdf 的 R 代码.

capture.output(cat("---
title: 'Test Results'
author: 'Tom & co.'
date: '11 10 2019'
output: pdf_document
---\n\n```{r setup, include=FALSE}\n
knitr::opts_chunk$set(echo = TRUE)\n
mtcars <- data.frame(mtcars)\n```\n"), file="_RMD/Tom.Rmd")  # here of course your own data

lapply(seq(mtcars), function(i) 
  capture.output(cat("# Model", i, "\n\n```{r chunk", i, ", comment='', echo=FALSE}\n\
                   print(summary(lm(mpg ~ ", names(mtcars)[i] ,", mtcars)))\n```\n"),
                 file="_RMD/Tom.Rmd", append=TRUE))

rmarkdown::render("_RMD/Tom.Rmd")

产生:

enter image description here

解决方案类型 2

当我们想在 rmarkdown 本身中自动输出多个模型摘要时,我们可以在 之间进行选择。 1. 选择块选项 results='asis'这将产生代码输出,但例如# Model 1头条新闻,或 2. 选择不选择它,这会产生 型号 1 但破坏了代码格式。解决方案是使用该选项并将其与我们可以使用的内联代码结合 paste()与另一个 sapply() -循环内sapply()对于模型。

在主 sapply我们应用@G.Grothendieck 的尊敬 solution很好地替代 Call:使用 do.call("lm", list(.)) 的输出行.我们需要包装一个 invisible(.)在它周围避免不必要的sapply()输出 [[1]] [[2]]...产生的空列表。

我包括了一个 ". "cat() , 因为像 ` this` 这样的前导空白将呈现为 this在摘要输出的第 6 行和第 10 行。

这是生成 *pdf 的 rmarkdown 脚本也可以逐行执行:
---
title: "Test results"
author: "Tom & co."
date: "15 10 2019"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
# Overview

This is an example of an ordinary code block with output that had to be included.

```{r mtcars, fig.width=3, fig.height=3}
head(mtcars)
```
# Test results in detail

The test results follow fully automated in detail.

```{r mtcars2, echo=FALSE, message=FALSE, results="asis"}
invisible(sapply(tail(seq(mtcars), -2), function(i) {
  fo <- reformulate(names(mtcars)[i], response="mpg")
  s <- summary(do.call("lm", list(fo, quote(mtcars))))
  cat("\n## Model", i - 2, "\n")
  sapply(1:19, function(j) 
    cat(paste0("`", ". ", capture.output(s)[j]), "`  \n"))
  cat("  \n")
  }))
```

***Note:*** This is a concluding remark to show that we still can do other stuff afterwards.

产生:

(注:站点 3 省略)

enter image description here

enter image description here

关于R Markdown,循环输出测试结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58283042/

相关文章:

r - 如何在 RMarkdown 文档中添加空格?

html - 在 R markdown 中嵌入 plotly 输出

r-markdown - 从 R Markdown 和 Knit 中删除 R 输出中的哈希值

plot - 在 R Markdown/knitr 中缩略图一些图的简单方法是什么?

r - 将函数应用于行但引用不同的表

r - 使用 R 计算数据集中每个组的正态性

r - 在ggplot2中手动缩放离散x轴变量

r - 如何找到至少2个向量中常见的元素?

r - Knit 钩子(Hook)在 tex 文件中的\documentclass 行之前添加代码,以避免选项与 xcolor 冲突

r - 如何输出模型系数的估计值?