0
votes

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.

Example

---
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"] ))
}
```

Output

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

Desired output

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

2

2 Answers

1
votes

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:

enter image description here

0
votes

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"] ))))
}

enter image description here```