r - maximum number of unique elements occurring for a given value in matrix -
suppose got data frame this:
> id = c(1,1,1,1,1,2,2,2,3,3) > type = c("a","a","b","c","a","a","b","c","a","c") > data = data.frame(id,type) > data id type 1 1 2 1 3 1 b 4 1 c 5 1 6 2 7 2 b 8 2 c 9 3 10 3 c
i find out maximum number of unique types per id, not maximum among values. there 1 liner in base package this? thank you.
you can try
library(data.table)#v1.9.5+ setdt(data)[, list(type=uniquen(type)) ,id]
or
library(dplyr) data %>% group_by(id) %>% summarise(type= n_distinct(type))
or using base r
aggregate(type~id, data, fun=function(x) length(unique(x)))
Comments
Post a Comment