How can I flag a row where a value appears in more than one group in R?

Viewed 68

I would like to add a column that indicates whether a value appears in more than one group. Using the below example, value '4' appears in groups '1' and '2', so I would like to flag that value.

x = matrix(c(1,1,1,2,2,2,3,3,4,4,5,4), nrow = 6, ncol = 2, byrow = F)
x = data.frame(x)
x

#   X1 X2
# 1  1  3
# 2  1  3
# 3  1  4
# 4  2  4
# 5  2  5
# 6  2  4

This would be the desired output:

#   X1 X2 FLAG
# 1  1  3  False  
# 2  1  3  False
# 3  1  4  True
# 4  2  4  True
# 5  2  5  False
# 6  2  4  True
3 Answers

We can create the flag by using n_distinct after grouping by 'X2'

library(dplyr)
x %>% 
     group_by(X2) %>% 
     mutate(FLAG = n_distinct(X1) > 1)

Here is a base R option using àve

transform(
  x,
  FLAG = ave(X1, X2, FUN = function(v) length(unique(v))) > 1
)

or aggregate + subset

transform(
  x,
  FLAG = X2 %in% subset(aggregate(. ~ X2, x, function(x) length(unique(x))), X1 > 1)$X2
)

which gives

  X1 X2  FLAG
1  1  3 FALSE
2  1  3 FALSE
3  1  4  TRUE
4  2  4  TRUE
5  2  5 FALSE
6  2  4  TRUE

For completion here is data.table version :

library(data.table)
setDT(x)[, FLAG := uniqueN(X1) > 1, X2]
x

#   X1 X2  FLAG
#1:  1  3 FALSE
#2:  1  3 FALSE
#3:  1  4  TRUE
#4:  2  4  TRUE
#5:  2  5 FALSE
#6:  2  4  TRUE
Related