Apply a function to a list of dataframes n list elements at a time

Solution 1:

As per comments, here's my suggestion without the group_split:

n_per_group = 3
mtcars %>%
  mutate(
    carb_grp = as.integer(factor(carb)),
    plot_grp = (carb_grp - 1) %/% n_per_group
  ) %>%
  group_by(plot_grp) %>%
  group_map(
    ~ggplot(., aes(x = disp, y = hp)) +
       geom_line()  +
       facet_wrap(carb ~ ., ncol = 1)
  )

In general, I find most of what I might want to do after group_split can be done with group_map instead, and there are sometimes advantages to keeping the data together---like ease of regrouping, as in this example.

Solution 2:

I think you should first look at solutions that do not require splitting then un-splitting ... but if you're stuck with it, then you can group them such as this:

ggs <- split(ldf, (seq_along(ldf)-1) %/% 3) %>%
  lapply(function(z) {
    bind_rows(z, .id = "column_label") %>%
      ggplot(aes(x = disp, y = hp)) +
      geom_line()  +
      facet_wrap(carb ~ ., ncol = 1)
  })

(Produces a list of 2 gg objects.)