Generate random groups with condition on other group column

Viewed 185

I have the following data with 10 IDs all being assigned to a group ranging between 1 and 5.

library(data.table)

df = data.table(ID = 1:10,
                Group_1 = c(1, 1, 1, 2, 3, 3, 4, 4, 5, 5))

 #     ID Group_1
 #  1:  1       1
 #  2:  2       1
 #  3:  3       1
 #  4:  4       2
 #  5:  5       3
 #  6:  6       3
 #  7:  7       4
 #  8:  8       4
 #  9:  9       5
 # 10: 10       5

Now I wish to randomly assign an additional group to each ID, again with a number ranging between 1 and 5. However, with the condition that Group_2 is not the same as Group_1.

ID Group_1 Group_2
 1       1       3
 2       1       5
 3       2       4
 4       2       1
 5       3       2
 6       3       2
 7       4       5
 8       4       1
 9       5       3
10       5       4
1 Answers

take a sample of the difference of 1:5 and the value of Group_1

set.seed(123) # <-- !! remove in production
df[, Group_2 := sample( setdiff( 1:5, Group_1 ), 1 ), by = 1:nrow(df)][]
#    ID Group_1 Group_2
# 1:  1       1       4
# 2:  2       1       4
# 3:  3       1       4
# 4:  4       2       3
# 5:  5       3       4
# 6:  6       3       2
# 7:  7       4       2
# 8:  8       4       2
# 9:  9       5       3
#10: 10       5       1
Related