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
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) )
})
```
Using asis, wrapping both the table and plot in print() and cat'ing a linefeed solve the interleaving problem. I haven’t figured how to combine this with the variable height plots from custom R Markdown plot size within loop
See https://github.com/yihui/knitr/issues/886
```{r cars, echo=FALSE, results='asis'}
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
for(one.possibility in carb.possibilities){
current.possibility <- filtereds[[one.possibility]]
my.ggplot <- 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) )
print(kable(current.possibility))
cat('\n')
print(my.ggplot)
}
```
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With