I have a data frame like
col1 col2 col3
A 2 b1
A 3 b2
A 2 b2
A 2 b1
A 3 b2
I want to get the count of unique values of col3 for each combination of col1 and col2 as following
col1 col2 count_unique
A 2 2
A 3 1
What is the best one line solution to this?
aggregate(col3~., df, function(x) length(unique(x)) )
but your desired output is wrong -- there's only one unique value for for col3 for the second row. – Frank?aggregate
documentation. I always use data.table for this:setDT(df)[, uniqueN(col3), by=.(col1,col2)]
– Frank