R Markdown,当块选项结果=" asis"时输出测试结果(htest)

时间:2017-10-24 06:42:49

标签: r knitr r-markdown pander

我需要使用results = "asis",原因如下:https://stackoverflow.com/a/36381976/

但是,使用该块选项意味着其他输出非理想地呈现。特别是我在输出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")
```

browser_screenshot

Pander使它最接近一个漂亮的显示但是错过了一些信息(置信区间)。也许有一种方法可以让它全部显示出来?

如何很好地显示prop.test和类似的输出?

2 个答案:

答案 0 :(得分:2)

您可以像这样使用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中。这里看起来是一个粗略的例子

enter image description here

答案 1 :(得分:2)

一种选择是返回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")
```