yuliaUU
yuliaUU

Reputation: 1723

knitr: generating summary tables with tabs in the loop?

I was trying to do the following using example , but i want to autogenerate the tab with summary table of lm() I created first the list with all summary tables: list_lm

---
title: 
author: 
date: 
output:
    html_document
---

# {.tabset}
```{r}
list_lm=list()
for(i in 1:10){
  list_lm[[i]]=  lm(dist ~ speed, data=cars)
}
```


```{r,results='asis', echo=FALSE}
for(i in 1:10){
  cat('##',i,' \n')
  print(list_lm[[i]] )
}
```

but it does not seem to produce a nice output when I do print(list_lm[[i]] )

https://stackoverflow.com/questions/24342162/regression-tables-in-markdown-format-for-flexible-use-in-r-markdown-v2

Upvotes: 3

Views: 1209

Answers (1)

Waldi
Waldi

Reputation: 41260

You could use knitr::kable to better format the output:

---
output:
  html_document
---
  
# {.tabset}
```{r}
list_lm=list()
for(i in 1:10){
  list_lm[[i]]=  lm(dist ~ speed, data=cars)
}
```


```{r,results='asis', echo=FALSE}
for(i in 1:10){
  cat('##',i,' \n')
  cat("Coefficients: \n")
  print(knitr::kable(list_lm[[i]]$coefficients)) 
  cat("\n")
  cat("Summary: \n")
  s <- summary(list_lm[[i]])
  print(knitr::kable(data.frame(sigma = s$sigma,r.squared=s$r.squared)) )
  cat('\n')
}
```

enter image description here

Another option is to use broompackage :

---
output:
  html_document
---

`r knitr::opts_chunk$set(echo = FALSE, warning = FALSE, message = FALSE, cache = F)`
  
# {.tabset}
```{r, ECHO = F, MESSAGE = F}
library(dplyr)
library(broom)
list_lm=list()
for(i in 1:10){
  list_lm[[i]]=  lm(dist ~ speed, data=cars)
}
```


```{r,results='asis', echo=FALSE}

for(i in 1:10){
  cat('##',i,' \n')
  list_lm[[i]] %>% tidy() %>% knitr::kable() %>% print
  cat('\n')
}
```

enter image description here

Upvotes: 2

Related Questions