Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Interleaving tables and plots in R Markdown, within loop

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) ) 
})
```
like image 865
Mark Miller Avatar asked Nov 09 '22 08:11

Mark Miller


1 Answers

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)

}
```
like image 119
Mark Miller Avatar answered Nov 15 '22 07:11

Mark Miller