我可以使用starts_with对列进行group_by吗?

And*_*w P 7 r dplyr tidyselect

我正在处理一个大数据框,其中有许多我想要分组的列。我想做这样的事情:

output <- df %>% 
  group_by(starts_with("GEN", ignore.case=TRUE),x,y) %>% 
  summarize(total=n()) %>% 
  arrange(desc(total))
Run Code Online (Sandbox Code Playgroud)

有没有办法做到这一点?也许使用 group_by_at 或其他类似的函数?

Ben*_*ris 9

要使用starts_with()in group_by(),您需要将其包装在 中across()。这是使用一些构建数据的示例。

library(dplyr)
mtcars %>%
group_by(across(starts_with("c"))) %>%
summarize(total = n()) %>%
arrange(-total)

# A tibble: 9 x 3
# Groups:   cyl [3]
    cyl  carb total
  <dbl> <dbl> <int>
1     4     2     6
2     8     4     6
3     4     1     5
4     6     4     4
5     8     2     4
6     8     3     3
7     6     1     2
8     6     6     1
9     8     8     1
Run Code Online (Sandbox Code Playgroud)