Remove items from a row from a list

I would like to create the last column ('wish_result') from the 3 previous columns ('group', 'animal' and 'full'). Below is the code for a 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)), by = '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, I would like to change β€œfull” so that it does not include the corresponding β€œanimal”. I tried various lapply commands using both lists and character versions of these columns, but could not solve this problem.

+6
source share
3 answers

Here's a possible approach

 data[, desired_result := { temp <- unique(unlist(full)) toString(temp[-match(animal, temp)]) }, by = .(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 
+3
source

Another option:

 data[, desired := .(Map(setdiff, list(animal), as.list(animal))), by = group] #or if starting from full data[, desired := .(Map(setdiff, full, animal))] 

(disposing of magic does the work of the first version)

+3
source

I also found a way!

By turning the "animal" into a list, I can use mapply.

 data$animal = strsplit(data$animal, ' ') data$check = mapply(function(x, y) {list(x[x != y]) }, data$full, data$animal) data group animal full desired_result check 1: 1 cat cat,dog,pig dog, pig dog,pig 2: 1 dog cat,dog,pig cat, pig cat,pig 3: 1 pig cat,dog,pig cat, dog cat,dog 4: 2 giraffe giraffe,lion,tiger lion, tiger lion,tiger 5: 2 lion giraffe,lion,tiger giraffe, tiger giraffe,tiger 6: 2 tiger giraffe,lion,tiger giraffe, lion giraffe,lion 
+1
source

All Articles