r - Remove row-specific items from list -
i create last column ('desired_result') 3 prior columns ('group', 'animal', , 'full'). below code reproducible example.
library(data.table) data = data.table(group = c(1,1,1,2,2,2), animal = c('cat', 'dog', 'pig', 'giraffe', 'lion', 'tiger'), desired_result = c('dog, pig', 'cat, pig', 'cat, dog', 'lion, tiger', 'giraffe, tiger', 'giraffe, lion')) data[, full := list(list(animal)), = 'group'] data = data[, .(group, animal, full, desired_result)] data group animal full desired_result 1: 1 cat cat,dog,pig dog, pig 2: 1 dog cat,dog,pig cat, pig 3: 1 pig cat,dog,pig cat, dog 4: 2 giraffe giraffe,lion,tiger lion, tiger 5: 2 lion giraffe,lion,tiger giraffe, tiger 6: 2 tiger giraffe,lion,tiger giraffe, lion
basically, modify 'full' not include corresponding 'animal'. have tried various lapply commands using both list , character versions of these columns have not been able solve problem.
here's possible approach
data[, desired_result := { temp <- unique(unlist(full)) tostring(temp[-match(animal, temp)]) }, = .(group, animal)] data # group animal full desired_result # 1: 1 cat cat,dog,pig dog, pig # 2: 1 dog cat,dog,pig cat, pig # 3: 1 pig cat,dog,pig cat, dog # 4: 2 giraffe giraffe,lion,tiger lion, tiger # 5: 2 lion giraffe,lion,tiger giraffe, tiger # 6: 2 tiger giraffe,lion,tiger giraffe, lion
Comments
Post a Comment