有没有一种简单的方法可以将 dplyr 汇总函数结果添加到每一行?

is there a simple way to add the dplyr summarize function result to every row?

以下是我的数据的简单版本:

如果 Column1 中至少有一个项目,我想为每个组创建一个标志。 我知道我可以在 dplyr 中执行此操作,然后将其与我的原始数据合并,但我想知道是否有更简单的方法。

例如,我可以这样做:

df_column <- df %>% filter(!is.na(Column1)) %>% group_by(Group)%>%
  summarize(n=n_distinct(Column1))

然后我可以将其与原始数据合并并创建一个标志。

没有filtering,我们可以用mutate通过在groupingby之后根据'Column1'中唯一元素(n_distinct)的数量创建一个逻辑列来做到这一点'Group'

library(dplyr)
df %>%
     group_by(Group) %>%
     mutate(flag = n_distinct(Column1[!is.na(Column1)]) > 1)

只是对之前使用 ifelse 的答案的重复,如果您来自 Excel(看起来您可能是),这可能更容易理解:

library(dplyr)

df %>%
    group_by(Group) %>% 
    mutate(flag = ifelse(
        is.na(column1),
        "flag",
        "dont_flag"
    ))