【问题标题】:dplyr- conditional and multiple filters grouped-bydplyr- 条件过滤器和多个过滤器分组
【发布时间】:2017-05-06 03:09:58
【问题描述】:

我想以一种具有 dplyr 感觉的可概括方式基于多个条件进行过滤。我的目标是过滤以获取组达到 40000 目标的第一个月。鉴于此数据。

group month    output cumulouput  indi
(fctr) (int)     (dbl)      (dbl) (dbl)
  A     1  9735.370    9735.37     0
  A     2 10468.063   20203.43     0
  A     3 11494.736   31698.17     0
  B     1 10186.465   10186.46     0
  B     2  9771.083   19957.55     0
  B     3  9871.636   29829.18     0
  B     4  9877.264   39706.45     0
  B     5  9009.198   48715.65     1
  B     6  9874.526   58590.17     1
  C     1 10613.868   10613.87     0
  C     2 10503.673   21117.54     0
  C     3 10397.098   31514.64     0
  C     4  9709.228   41223.87     1
  C     5  9861.669   51085.54     1
  C     6  9137.551   60223.09     1

对于每个组是得到组达到目标的最小月份和组没有达到目标的最大月份。 (???)

这是过滤的结果:

group   month    output cumulouput  indi
(fctr) (int)     (dbl)      (dbl) (dbl)
  A     3 11494.736   31698.17     0
  B     5  9994.509  51800.365     1
  C     4  9709.228   41223.87     1

对于数据:

library(dplyr)
df1 <- data.frame(group = rep(LETTERS[1:3], each=6),  month = rep(1:6,3))     %>% 
arrange(group,month) %>% 
mutate(output = rnorm(n=18,mean = 10000, sd = 722))%>%
group_by(group) %>%
mutate(cumulouput=cumsum(output))%>% 
filter(!(group=="A"&month>=4)) %>% 
mutate( indi= ifelse(cumulouput>40000,1,0))

【问题讨论】:

    标签: r filter dplyr


    【解决方案1】:

    这将为您提供所需的输出,尽管我觉得它可以缩短一点。

    library(dplyr)
      df1 <- data.frame(group = rep(LETTERS[1:3], each=6),  month = rep(1:6,3))     %>% 
      arrange(group,month) %>% 
      mutate(output = rnorm(n=18,mean = 10000, sd = 722))%>%
      group_by(group) %>%
      mutate(cumulouput=cumsum(output))%>% 
      filter(!(group=="A"&month>=4)) %>% 
      mutate( indi= ifelse(cumulouput>40000,1,0))
    
    one <- df1 %>%
      group_by(group) %>%
      .[.$cumulouput > 40000,] %>% 
      filter(row_number(cumulouput) == 1)
    
    two <- df1 %>%
      group_by(group) %>%
      .[.$indi == 0,]
    
    three <- rbind(one,two) %>%
      group_by(group) %>%
      filter(cumulouput == max(cumulouput))%>%
      arrange(group)
    
    head(three)
    

    【讨论】:

    • 如果没有达到目标,这不会显示最大月份
    【解决方案2】:

    这里的逻辑如下,对于每一行的每个group,它检查是否indi==1 如果TRUE 它返回min 月份,如果FALSE 它返回max 月份,则目标满足目标不满足。 然后filtermonths 与我们刚刚添加的匹配,filtermax(indi) 删除前几个月的group。 最后删除 temp 列m

    df1 %>% group_by(group) %>%
        mutate(m=if_else(indi==1, min(.[.$indi==1,'month']), max(.[.$indi==0,'month']))) %>% 
        filter(month==m, indi==max(indi)) %>%
        select(-m)
    

    【讨论】:

    • 您好 Mabdrabo,逻辑很好,但我尝试了但没有显示所需的输出。因为 de temp m colum 每行只显示 4.。
    猜你喜欢
    • 2021-10-25
    • 1970-01-01
    • 2016-02-16
    • 2019-10-10
    • 2019-09-21
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多