Q:

r - maximum number of unique elements occurring for a given value in matrix

Suppose I got a data frame like 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    a
2   1    a
3   1    b
4   1    c
5   1    a
6   2    a
7   2    b
8   2    c
9   3    a
10  3    c

I would like to find out what is the maximum number of unique types per id, but NOT the maximum among the values. Is there a one liner in the base package for this? Thank you.

A:

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)))

