R Markdown,当chunk option results="asis"时输出测试结果(htest)

R Markdown, output test results (htest) when chunk option results="asis"

我需要使用 results = "asis",原因如下:

但是,使用该块选项意味着其他输出呈现不理想。具体来说,我在输出 prop.test 结果时遇到问题,但我确信其他数据类型也会出现这种情况。

我在下面的示例中提供了 4 个选项,所有选项都在某些方面有所不足:

---
title: "R Notebook"
output:
  html_document:
    df_print: paged
---
```{r, echo=F, message=F, warning=F, results="asis"}
library(knitr)
library(pander)
out <- prop.test(c(10,30), c(20,40))
cat("# Header  \n")
cat("  \n## Straight output\n")
out # Only properly renders first line
cat("  \n## Print\n")
print(out) # Only properly renders first line
cat("  \n## Kable\n")
#kable(out) # Will fail: Error in as.data.frame.default(x) :   cannot coerce class ""htest"" to a data.frame
kable(unlist(out)) # Renders everything but in an ugly way
cat("  \n## Pander\n")
pander(out) # Misses confidence interval.
cat("  \n As you can see, Pander misses some information, such as the confidence interval")
```

Pander 使其最接近漂亮的显示但遗漏了一些信息(置信区间)。或许有办法让它显示全部?

我怎样才能很好地显示 prop.test 和类似的输出?

你可以这样使用formattable

library(knitr)
library(formattable)
out <- prop.test(c(10,30), c(20,40))
cat("# Header  \n")
cat("  \n## Straight output\n")
out # Only properly renders first line
cat("  \n## Print\n")
print(out) # Only properly renders first line
cat("  \n## Kable\n")
#kable(out) # Will fail: Error in as.data.frame.default(x) :   cannot coerce class ""htest"" to a data.frame
kable(unlist(out)) # Renders everything but in an ugly way
cat("  \n## Pander\n")

df <- data.frame(value = unlist(out))
tdf <- as.data.frame(t(df))
formattable(tdf)

您可以保留所需的列,更新列名,因为所有这些都在 data frame 中。这里有一个粗略的示例

一个选项是 return 到 results = "markup"(默认值),并将您的 cat 调用替换为 asis_output(来自 knitr 包)。

---
title: "R Notebook"
output:
  html_document:
    df_print: paged
---
```{r, echo=F, message=F, warning=F}
library(knitr)
library(pander)
out <- prop.test(c(10,30), c(20,40))
asis_output("# Header  \n")
asis_output("  \n## Straight output\n")
out # Only properly renders first line
asis_output("  \n## Print\n")
print(out) # Only properly renders first line
asis_output("  \n## Kable\n")
#kable(out) # Will fail: Error in as.data.frame.default(x) :   cannot coerce class ""htest"" to a data.frame
kable(unlist(out)) # Renders everything but in an ugly way
asis_output("  \n## Pander\n")
pander(out) # Misses confidence interval.
asis_output("  \n As you can see, Pander misses some information, such as the confidence interval")
```