gpt4 book ai didi

从列表中删除特定于行的项目

转载 作者:行者123 更新时间:2023-12-04 10:40:07 25 4
gpt4 key购买 nike

我想从前 3 个列(“组”、“动物”和“完整”)创建最后一列(“desired_result”)。以下是可重现示例的代码。

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

基本上,我想修改“完整”,使其不包括相应的“动物”。我尝试了使用这些列的列表和字符版本的各种 lapply 命令,但未能解决此问题。

最佳答案

这是一种可能的方法

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

关于从列表中删除特定于行的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31172299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com