dplyr- group by in a for loop r [closed]

。_饼干妹妹 提交于 2021-02-08 10:20:21

问题


I am trying to use group by in a for loop. I would like the gourp by to cycle through each column and then I can perform a summarise action. I tried to used colnames(df[i]) within the groupby but because colnames comes back with quotation marks this method does not work.

Any suggestions?


回答1:


If you aren't dead set on using a for loop, the easiest way may be to use dplyr::summarise_all or dplyr::sumarise_at - depending on your needs.

df <- tibble(
  var1 = c(rep("a", 5), rep("b", 5)),
  var2 = rnorm(10),
  var3 = rnorm(10)
)

df %>% 
  group_by(var1) %>% 
  summarise_all(funs(mean = mean))

# A tibble: 2 x 3
   var1  var2_mean  var3_mean
  <chr>      <dbl>      <dbl>
1     a -0.2715518 -0.6146812
2     b  0.1502118 -0.2061952

Update:

Sorry, I previously misread the question. You want to loop over the "group_by" variables - not the response variables.

You can do that with tidy eval. Here is an example:

df <- tibble(
  var1 = c(rep("a", 5), rep("b", 5)),
  var2 = c(rep("c", 3), rep("d", 7)),
  var3 = rnorm(10)
)

groups <- c(quo(var1), quo(var2))  # Create a quoture

for (i in seq_along(groups)) {
  df %>% 
    group_by(!!groups[[i]]) %>% # Unquote with !!
    summarise(mean = mean(var3)) %>% 
    print()
}

# A tibble: 2 x 2
   var1       mean
  <chr>      <dbl>
1     a -0.3451196
2     b  0.4117763
# A tibble: 2 x 2
   var2       mean
  <chr>      <dbl>
1     c -0.2618434
2     d  0.1598305


来源:https://stackoverflow.com/questions/47367579/dplyr-group-by-in-a-for-loop-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!