根据向量重叠从列表中删除元素并将元素添加到列表 [英] removing and appending elemets from and to a list based on a vector overlap

查看:73
本文介绍了根据向量重叠从列表中删除元素并将元素添加到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含约500个模型对象的列表.该对象的名称为v1:

I have a list with ~ 500 model objects. The names of this objects are v1:

existing.list <- vector("list", 3)
v1 <- names(existing.list) <- c("A", "B", "C")

我现在得到了不同的数据集,我也需要对其进行建模,并将其保存在同一列表中.此新数据集中的对象与existing.list中的某些对象重叠.因为这非常耗时,所以我确实想保留旧的结果.此新数据集的名称为v2:

I now get different dataset, which i need to model, too, and save in the same list. The objects in this new dataset are overlapping with the some of the objects in existing.list. Because it is very time-consuming, i do want to keep the old results. The names of this new dataset are v2:

v2 <- c("B", "C", "D")

我首先要删除v1中的对象,而不是v2中的对象,然后将其附加到现存.列出v2中所有新的唯一名称. 我可以用相当复杂的方式完成第一个任务:

I first want to remove the objects in v1, which are not in v2, then append to existing.list all the new, unique names from v2. I can do the first task in a rather complicated way:

rm <- v1[!v1 %in% v2]
rm.i <- which(v1 %in% rm)
v1 <- v1[-rm.i]

但是后来我无法追加新对象,这取决于v2中的唯一元素:

But then i fail at appending the new objects, as determined by the unique elements in v2:

new.elements <- v2[!v2 %in% v1]

所需的输出是修改后的existing.list,具有完整的元素"B"和"C"以及新的空元素"D".基本上,它是一个列表,其中的元素由v2中的名称确定,但是由于多种原因,仅创建一个新列表并将existing.list的一部分复制到其中会很复杂. 由于我需要针对多个列表执行此操作,因此比我现在更简单的方法将很方便.

The desired output is a modified existing.list, with intact elements "B" and "C" and a new empty element "D". Basically, its a list with elements determined by the names in v2, but for a number of reasons it would be complicated to just create a new list and copy parts of existing.list to it. Since i need to do this for a number of lists, a less complicated way than i am doing now would be handy.

非常感谢您!这是项目的最后一分钟,因此对您的帮助深表感谢!

Thank you very much in advance! This is a last minute addition to a project, so any help is highly appreciated!

此问题基于上一个问题,我用草率的措词造成了混乱.感谢那些仍在努力帮助我的用户.

this question is based on a previous question, which i sloppily worded and thus created confusion. My thanks to those users, who still tried to help me.

推荐答案

如果我对您的理解正确,那么您可以首先获取v2中而不是v1

If I understood you correctly you can first get the names of elements that are in v2 but not in v1

tmp <- setdiff(v2, v1) # "D"

然后是子集existing.list并按如下所示附加它

And then subset existing.list and append it as follows

existing.list <- c(existing.list[v1 %in% v2], 
                   setNames(vector("list", length(tmp)), tmp))

结果

existing.list
#$B
#NULL

#$C
#NULL

#$D
#NULL

这篇关于根据向量重叠从列表中删除元素并将元素添加到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆