Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to use results = "asis" for reasons stated here: https://stackoverflow.com/a/36381976/

However, using that chunk option means other outputs render non-ideally. Specifically I'm having issues outputting prop.test results, but I'm sure this would happen for other data types.

I've provided 4 options in the example below, all of which fall short in some way:

---
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 gets it closest to a nice display but misses some information (confidence interval). Perhaps there's a way to make it display all?

How can I nicely display the output of prop.test and similar?

like image 264
conor Avatar asked Oct 19 '25 09:10

conor


1 Answers

One option is to return to results = "markup" (the default) and replace your cat calls with asis_output (from the knitr package).

---
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")
```
like image 91
Benjamin Avatar answered Oct 20 '25 23:10

Benjamin