I'm trying to use RMarkdown/R Notebooks to produce an automated report based on a single dataset broken out by department. Intuitively, I want to use a for
loop that filters the dataset to a single department, provides a title, displays a few graphs and tables specific to that deparment, and then produces a page break and starts with the next department.
Here's a reprex of what I have so far. Problems with the resulting code:
- There are blank spaces throughout, pretty sure related to the use of
dev.off()
andplot.new()
. If I remove these, only the first plot prints and the titles print all together in a bunch at the beginning. If I include thedev.off
andplot.new
calls, then I get blank graphics placeholders. - There are NA items throughout. I'm not sure why. They don't appear when running the code in RStudio, only in the resulting output.
- I can't get headers to work and act like H1, H2 etc. headers. They are rendered as code output.
Am I approaching this wrong? Should I not use a for loop, but do something else instead? If I take everything out of the loop and do it manually, it works great.
```
---
title: "Demo Notebook"
output:
word_document: default
---
```{r echo=FALSE, message=FALSE, warning=FALSE, paged.print=TRUE, results= "asis"}
library(tidyverse)
library(knitr)
spp <- unique(iris$Species)
for (i in seq_along(spp)) {
print(paste0("# Species: ", spp[i]))
d <- iris %>%
filter(Species == spp[i])
# one kind of plot
p <- ggplot(d, aes(x = Sepal.Length, y = Sepal.Width)) +
geom_smooth() +
ggtitle(spp[i])
print(p)
dev.off()
plot.new()
# another plot
q <- plot(d$Sepal.Length)
print(q)
dev.off()
# a table
print(kable(head(d)))
}
```
# Species: ", spp[x], "")). However, a [1]" floats above my title and a random " mark appears at the end of my title. Getting closer, though.
– datakritter Feb 14 '20 at 19:58