I wish to count the number of unique values by grouping of a second variable, and then add the count to the existing data.frame as a new column. For example, if the existing
This can be also achieved in a vectorized without by group operations by combining unique with table or tabulate
If df$color is factor, then
Either
table(unique(df)$color)[as.character(df$color)]
# black black black green green red red blue blue blue
# 2 2 2 1 1 2 2 3 3 3
Or
tabulate(unique(df)$color)[as.integer(df$color)]
# [1] 2 2 2 1 1 2 2 3 3 3
If df$color is character then just
table(unique(df)$color)[df$color]
If df$color is an integer then just
tabulate(unique(df)$color)[df$color]