I would like to create the last column ('desired_result') from the 3 prior columns ('group', 'animal', and 'full'). Below is 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 modify 'full' so it does not include the corresponding 'animal'. I have tried various lapply commands using both list and character versions of these columns but have not been able to solve this problem.
There are three ways in which you can Remove elements from List: Using the remove() method. Using the list object's pop() method. Using the del operator.
DataFrame. drop() method you can remove/delete/drop the list of rows from pandas, all you need to provide is a list of rows indexes or labels as a param to this method. By default drop() method removes the rows and returns a copy of the updated DataFrame instead of replacing the existing referring DataFrame.
How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.
Use the list. pop() method to remove a string from a list, e.g. my_list. pop(0) .
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
Another option:
data[, desired := .(Map(setdiff, list(animal), as.list(animal))), by = group]
#or if starting from full
data[, desired := .(Map(setdiff, full, animal))]
(recycling magic makes the first version work)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With