dplyr n_distinct with condition

前端 未结 4 1536
离开以前
离开以前 2021-02-05 17:39

Using dplyr to summarise a dataset, I want to call n_distinct to count the number of unique occurrences in a column. However, I also want to do another summarise() for all uniqu

4条回答
  •  被撕碎了的回忆
    2021-02-05 18:18

    We can also use aggregate from base R

     aggregate(cbind(count=A)~B, a, FUN=function(x) length(unique(x)))
     #  B count
     #1 N 1
     #2 Y 2
    

    Based on the OP's expected output

     data.frame(count=length(unique(a$A)), 
                count_BisY = length(unique(a$A[a$B=="Y"])))
    

提交回复
热议问题