Reputation: 6222
I tried to get the summary statistics of a number of variables in my data using a loop in Rmarkdown.
(I am using a loop as I am plotting the histograms etc as well, and results='asis'
option so that I can implement raw Rmarkdown for section titles inside the loop.)
The problem is that when I print the summary statistics, the column numbers and the starts appear on the same line as in the below example. I prefer to have the respective values under the corresponding column name.
---
title: "test"
author: "me"
date: "3 June 2019"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, results='asis'}
for (i in 1 : 3) {
cat('\n')
print(summary(iris[i*50 : 50, "Sepal.Length"] ))
}
```
Min. 1st Qu. Median Mean 3rd Qu. Max. 5 5 5 5 5 5
Min. 1st Qu. Median Mean 3rd Qu. Max. 5.7 5.7 5.7 5.7 5.7 5.7
Min. 1st Qu. Median Mean 3rd Qu. Max. 5.9 5.9 5.9 5.9 5.9 5.9
Min. 1st Qu. Median Mean 3rd Qu. Max. 5 5 5 5 5 5 Min. 1st Qu. Median Mean 3rd Qu. Max. 5.7 5.7 5.7 5.7 5.7 5.7 Min. 1st Qu. Median Mean 3rd Qu. Max. 5.9 5.9 5.9 5.9 5.9 5.9
I have tried with xtable
and knitr::kable
, but I couldn't get the desired output. xtable
require tables of > 2 dimensions
Upvotes: 0
Views: 6930
Reputation: 6222
Since the xtable
was complaining about not having enough rows, I have transposed the output from the summary
function. It worked.
---
title: "test"
author: "me"
date: "3 June 2019"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
library(xtable)
options(xtable.comment = FALSE)
```
```{r, results='asis'}
for (i in 1 : 3) {
cat('\n')
cat(paste0("#The Title ", i, " \n"))
print(xtable(t(summary(iris[i*50 : 50, "Sepal.Length"] ))))
}
Upvotes: 0
Reputation: 160397
The knitr
chunk option results="asis"
presumes that the output will be output "as is", intending that "you can write out raw Markdown text from R code (like cat('**Markdown** is cool.\n')
)" (from https://bookdown.org/yihui/rmarkdown/r-code.html).
Perhaps change it to
---
title: "test"
author: "me"
date: "3 June 2019"
output: pdf_document
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
```{r, comment=""}
for (i in 1 : 3) {
cat('\n')
print(summary(iris[i*50 : 50, "Sepal.Length"] ))
}
```
Output:
Upvotes: 1