如何添加到 group_by_at dplyr 函数中的分组

unk*_*own 4 grouping group-by r dplyr tidyverse

尝试使用 dplyr 将分组添加到具有现有分组的 tibble,但 group_by_at() 中的“添加”似乎不起作用。有谁知道为什么?

例子:

df <- data.frame(col1 = sample(letters,100,replace = T),
                 col2 = sample(letters,100,replace = T),
                 col3 = sample(letters,100,replace = T))

# group_by_at add doesn't work as desired:
df %>%
  group_by(col1) %>%
  group_by_at('col2', add = T) %>%
  summarise(n = n()) 

# but group_by add does work as desired:
df %>%
  group_by(col1) %>%
  group_by(col2, add = T) %>%
  summarise(n = n())
Run Code Online (Sandbox Code Playgroud)

akr*_*run 5

我们需要.add的,而不是add作为Usage中建议?group_by_atIS

group_by_at(.tbl, .vars, .funs = list(), ..., .add = FALSE, .drop = group_drops(.tbl))

df %>%
  group_by(col1) %>%
   group_by_at('col2', .add = TRUE) %>%
   summarise(n = n()) 
Run Code Online (Sandbox Code Playgroud)

NOTE: After the summarise step, one of the grouping variables are removed especially the last grouping variable

  • 伟大的!有史以来最快的答案。你知道为什么是 .add 而不是 add 吗? (3认同)