I have a R Markdown/knittr document that generates pairs of plots and tables. The number of pairs is variable, so I create them inside of a loop. I would like the results to be interleaved in the output: table 1, plot 1, table 2, plot 2...
In the example below, all tables come first at the top of the document. I have tried various permutations of
- pander or kable as my table function
- wrapping the table function in print or leaving it bare
- with or without results='asis'
EDIT: I found a solution and posted it below. Now I'm looking for one that's compatible with the great variable-height advice I received in custom R Markdown plot size within loop ?
```{r cars, echo=FALSE}
library(ggplot2)
library(knitr)
carb.possibilities <- sort(unique(as.character(mtcars$carb)))
filtereds <- lapply(carb.possibilities, function(carb.ct) {
return(mtcars[ mtcars$carb == carb.ct , ])
})
carb.possibilities <- paste(carb.possibilities, ' Carburetors', sep = '')
names(filtereds) <- carb.possibilities
lapply(carb.possibilities, function(one.possibility) {
current.possibility <- filtereds[[one.possibility]]
print(kable(current.possibility))
ggplot(current.possibility, aes(factor(gear), mpg)) +
coord_flip() +
labs(x = "Gears", title = one.possibility) +
geom_point(position=position_jitter( width = 0.1, height = 0.1) )
})
```
for(one.possibility in carb.possibilities){
, instead of lapply, and the nprint(ggplot(...))
do.call(grid.arrange...)
in the answer I linked.