Conditionally Count in dplyr

前端 未结 3 976
闹比i
闹比i 2020-12-07 16:26

I have some member order data that I would like to aggregate by week of order.

This is what the data looks like:

memberorders=data.frame(MemID=c(\'A\         


        
相关标签:
3条回答
  • 2020-12-07 17:11

    Using the plyr package one could do

    ddply(memberorders,.(MemID),
                        summarise, 
                        val1 = sum(value[week<=2]), 
                        val2 = sum(value[week<=4]),
                        val3 = length(value[week<=2]),
                        val4 = length(value[week<=4]))
    
      MemID val1 val2 val3 val4
    1     A   30   30    2    2
    2     B   10   20    1    2
    3     C    5   35    1    2
    4     D    3    3    1    1
    
    0 讨论(0)
  • 2020-12-07 17:14

    Using both previews ideas and keeping it consistent:

    MemberLTV_2 <- memberorders %>%
    
    group_by(MemID) %>%
    summarize(
    
        count2 = length(value[week<=2]),
        count4 = length(value[week<=4]),
        sum2 = sum(value[week<=2]),
        sum4 = sum(value[week<=4])
    
        )
    
    0 讨论(0)
  • 2020-12-07 17:22

    Try

     library(dplyr)
     memberorders %>% 
            group_by(MemID) %>% 
            summarise(sum2= sum(value[week<=2]), sum4= sum(value[week <=4]), 
                      count2=sum(week<=2), count4= sum(week<=4))
    
    0 讨论(0)
提交回复
热议问题