【问题标题】:Filter in group_by + mutate not working as in group_by + summarise in dplyr R过滤 group_by + mutate 不像 group_by + summarise 在 dplyr R
【发布时间】:2020-06-11 13:51:56
【问题描述】:

我在使用tidyverse变异数据框时遇到过滤问题:

sample.df <- data.frame(
  group = c("A", "A", "A", "B", "B", "C"),
  value = c(1,2,3,4,5,6)
)

mutated.sample.df <- sample.df %>% 
  dplyr::group_by(group) %>% 
  dplyr::mutate(group_count = n()) 

non.desired.df <- mutated.sample.df %>% 
  dplyr::filter(group_count == max(group_count)) %>% 
  dplyr::select(-group_count)

这会返回一个不需要的解决方案,因为没有应用过滤器:

 group value
  <fct> <dbl>
1 A         1
2 A         2
3 A         3
4 B         4
5 B         5
6 C         6

另一方面,直接使用总结过滤器被正确应用:

summarized.sample.df <- sample.df %>% 
  dplyr::group_by(group) %>% 
  dplyr::summarise(group_count = n()) %>% 
  dplyr::filter(group_count == max(group_count))

给予:

 group group_count
  <fct>       <int>
1 A               3

我现在可以过滤原始数据框并获得我想要的 df:

desired.df <- sample.df %>% 
  dplyr::filter(group %in% summarized.sample.df$group)

即:

  group value
  <fct> <dbl>
1 A         1
2 A         2
3 A         3

我在 mutating 行为中遗漏了什么?我可以只过滤“硬编码”值:

my.max <- max(mutated.sample.df$group_count)
desired.df <- mutated.sample.df %>% 
  dplyr::filter(group_count == my.max) %>% 
  dplyr::select(-group_count)

是否有可能在一个管道中获得所需的.df?在总结和变异 hard 计算 max 我不能。

我希望这会起作用,但事实并非如此。任何提示为什么?

mutated.sample.df <- sample.df %>% 
  dplyr::group_by(group) %>% 
  dplyr::mutate(group_count = n()) %>% 
  dplyr::filter(group_count == max(group_count)) %>% 
  dplyr::select(-group_count)

谢谢

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    你可以这样做:

    sample.df %>%
     add_count(group) %>%
     filter(n == max(n)) %>%
     select(-n)
    
      group value
    1     A     1
    2     A     2
    3     A     3
    

    【讨论】:

      【解决方案2】:

      来自@tmfmnk 的代码更好,但您的管道无法正常工作,因为您忘记了“ungroup()”突变和过滤器之间的数据帧,因此“filter()”在组内工作。试试:

      mutated.sample.df <- sample.df %>% 
        dplyr::group_by(group) %>% 
        dplyr::mutate(group_count = n()) %>% 
        dplyr::ungroup()  %>% 
        dplyr::filter(group_count == max(group_count)) %>% 
        dplyr::select(-group_count)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多