Calculate proportion of positives values by group

前端 未结 3 467
生来不讨喜
生来不讨喜 2021-01-16 12:16

With this dataframe:

table <- \"
    trt rep ss  d1  d4  d5  d6  d7
    1   1   1   0   0   0   0   0
    1   1   2   0   0   0   0   0
    1   1   3   0          


        
3条回答
  •  孤城傲影
    2021-01-16 12:39

    Thanks to @A.Webb, here's a way in base R:

    aggregate(d[,4:8]>0~d$trt, FUN = mean)
    
    #   d$trt d1        d4        d5        d6        d7
    # 1     1  0 0.2222222 0.4444444 0.5555556 0.5555556
    # 2     2  0 0.0000000 0.0000000 0.3750000 0.5000000
    

    Here was my original idea:

    rowsum(+(d[-(1:3)] > 0), d$trt, na.rm=TRUE) / 
      rowsum(+!is.na(d[-(1:3)]), d$trt, na.rm=TRUE)
    

    The + is there because rowsum only works with numbers, and not with logicals.

提交回复
热议问题