Make Variable With Number of Unique Case by a Grouping Var

Viewed 36

I want to create a variable indicating there is at least one observation in each two-way table of two variables

I am working with panel data and want to know which observations are part of a group not represented in every year. Here is example data:

library( data.table)    
iris <- data.table( iris )
iris$grp <- sample( 1:15 , nrow( iris ) , replace=T)

I know how to create a table with the number of unique Species * Grp cells. I know that I can merge this back on to the data.table but it seems like there must be an easy way to create a variable directly. I have been trying to use the length() function but that isn't right. Essentially I want N in this table to be a variable in my data table. The answer needs to be in data.table

unique( iris[ , .( Species , grp ) ])[ , .N , by=Species]
2 Answers

If we need to join

iris[unique( iris[ , .( Species , grp ) ])[ , .N , by=Species],
     N := N, on = .(Species)]

Another option:

iris[, N := uniqueN(grp), Species]

FWIW, data.table:::unique.data.table has a by argument so you can use unique(iris, by=c("Species","grp")) for unique(iris[, .(Species, grp)])

Related