Home > Mobile >  Apply a function to a list of dataframes n list elements at a time
Apply a function to a list of dataframes n list elements at a time

Time:01-22

I have a dataframe that contains a grouping variable. Trivial to create a list of dataframes using group_split but then I'd like to turn around and make a plot that groups these 5 at a time using facetting. For reproducibility I'll use mtcars

ldf <- mtcars %>%
  group_split(carb)

Now I'm having a brain lock on how to do the equivalent of:

ldf[1:3] %>% 
  bind_rows( .id = "column_label") %>%
  ggplot(aes(x = disp, y = hp))  
  geom_line()   
  facet_wrap(carb ~ ., ncol = 1)

ldf[4:6] %>% 
  bind_rows( .id = "column_label") %>%
  ggplot(aes(x = disp, y = hp))  
  geom_line()   
  facet_wrap(carb ~ ., ncol = 1)

Where I don't have to manually slice the list with [1:3], [4:6] etc. and simply provide an n value like 3 or 5.

Preference for a tidyverse solution second choice base r. Thank you in advance

CodePudding user response:

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.

CodePudding user response:

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.)

  •  Tags:  
  • Related