This is a follow-up question to this one.
In the aforementioned question I could nicely implement a heading creating and the printing of a ggplot2 object in a loop.
Now I have a new problem: I need to print the summary of a model in the loop too. The problem is that it doesn't work if I have the asis
option.
Any ideas?
[Reprex:]
---
title: "Untitled"
output:
html_document:
theme: united
highlight: tango
toc: true
toc_float:
collapsed: false
smooth_scroll: false
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = FALSE, message = FALSE, warning = FALSE)
```
```{r}
library(dplyr)
library(ggplot2)
df <- datasets::iris %>%
dplyr::as_tibble()
```
```{r species_loop, results='asis'}
for(i in c("setosa", "versicolor", "virginica")) {
cat(paste0("\n\n## ", i, "\n"))
df_filtered <- df %>%
dplyr::filter(Species == i)
p <- df_filtered %>%
ggplot2::ggplot(ggplot2::aes(Sepal.Length, Petal.Length)) +
ggplot2::geom_point()
print(p)
my_model <- lm(Sepal.Length ~ Petal.Length, data = df_filtered)
summary(my_model) %>%
print()
}
```
## I need the printing output of the model to look like this:
```{r}
df_filtered <- df %>%
dplyr::filter(Species == "setosa")
my_model <- lm(Sepal.Length ~ Petal.Length, data = df_filtered)
summary(my_model) %>%
print()
```