34
ID= c('A', 'A', 'A', 'B', 'B', 'B')
color=c('white', 'green', 'orange', 'white', 'green', 'green')

d = data.frame (ID, color)

My desired result is

unique_colors=c(3,3,3,2,2,2)
d = data.frame (ID, color, unique_colors)

or more clear in a new dataframe c

ID= c('A','B')
unique_colors=c(3,2)
c = data.frame (ID,unique_colors)

I've tried different combinations of aggregate and ave as well as by and with and I suppose it is a combination of those functions.

The solution would include:

length(unique(d$color))

to calculate the number of unique elements.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
rmuc8
  • 2,869
  • 7
  • 27
  • 36
  • 1
    See also [**here**](http://stackoverflow.com/questions/17421776/how-to-add-count-of-unique-values-by-group-to-r-data-frame/17421925#17421925), (somewhat similar title on that Q...did you search before posting?) for additional possibilities – Henrik Jan 27 '15 at 15:28

1 Answers1

93

I think you've got it all wrong here. There is no need neither in plyr or <- when using data.table.

Recent versions of data.table, v >= 1.9.6, have a new function uniqueN() just for that.

library(data.table) ## >= v1.9.6
setDT(d)[, .(count = uniqueN(color)), by = ID]
#    ID count
# 1:  A     3
# 2:  B     2

If you want to create a new column with the counts, use the := operator

setDT(d)[, count := uniqueN(color), by = ID]

Or with dplyr use the n_distinct function

library(dplyr)
d %>%
  group_by(ID) %>%
  summarise(count = n_distinct(color))
# Source: local data table [2 x 2]
# 
#   ID count
# 1  A     3
# 2  B     2

Or (if you want a new column) use mutate instead of summary

d %>%
  group_by(ID) %>%
  mutate(count = n_distinct(color))
David Arenburg
  • 91,361
  • 17
  • 137
  • 196
  • 1
    And a poor man's function would be `with(d, ave(as.numeric(color), ID, FUN=function(x) length(unique(x))))` – akrun Jan 27 '15 at 15:26
  • @akrun you can probably post this as an alternative. – David Arenburg Jan 27 '15 at 15:26
  • @DavidArenburg David, Maybe In missing something obvious, but I am trying to use uniqueN with the most recent version of data.table and it is saying that the package does not exist. You have any ideas – MatthewR Jun 21 '15 at 21:41
  • @MatthewR yes, as I mentioned, this function present only in the development version on GitHub. Please follow the link I provided. – David Arenburg Jun 22 '15 at 04:06
  • This also works: d %>% group_by(ID) %>% mutate(count = n()) – aliawadh980 Jan 02 '19 at 17:00