user3647872
user3647872

Reputation: 95

Test if character values are all equal by group for data.table

Here's the problem. How does one test if all the values for each group have the same chaarcter values in a column.

For example

DTT<-data.table(id=rep(seq(1:1000), each = 1000), CHAR=rep("A",10000), key="id")

This would be true because all values for the column CHAR are the same for all ids

Upvotes: 1

Views: 176

Answers (1)

ThomasIsCoding
ThomasIsCoding

Reputation: 102890

We can also try unique + .N like below

> unique(DTT)[, .N == 1, id]
        id   V1
   1:    1 TRUE
   2:    2 TRUE
   3:    3 TRUE
   4:    4 TRUE
   5:    5 TRUE
  ---
 996:  996 TRUE
 997:  997 TRUE
 998:  998 TRUE
 999:  999 TRUE
1000: 1000 TRUE

Or use

DTT[,uniqueN(CHAR, na.rm = TRUE) == 1, id]
DTT[, if(uniqueN(CHAR, na.rm = TRUE) == 1) .SD, id]

Upvotes: 2

Related Questions