简体   繁体   English

一次将 function 应用于数据帧列表 n 列表元素

[英]Apply a function to a list of dataframes n list elements at a time

I have a dataframe that contains a grouping variable.我有一个包含分组变量的 dataframe。 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.使用group_split创建数据帧列表很简单,但是我想转身制作一个 plot 使用分面一次将这 5 个分组。 For reproducibility I'll use mtcars为了重现性,我将使用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.我不必手动使用 [1:3]、[4:6] 等对列表进行切片,只需提供像 3 或 5 这样的 n 值。

Preference for a tidyverse solution second choice base r.偏好 tidyverse 解决方案第二选择基地 r。 Thank you in advance先感谢您

As per comments, here's my suggestion without the group_split :根据评论,这是我没有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.一般来说,我发现在group_split之后我可能想做的大部分事情都可以用group_map代替,而且有时将数据保持在一起也有好处——比如易于重组,如本例所示。

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.) (生成 2 个gg对象的list 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM