基于向量重叠从列表中删除和附加元素 [英] removing and appending elemets from and to a list based on a vector overlap
问题描述
我有一个包含约 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 中所有新的、唯一的名称附加到 existing.list.我可以用相当复杂的方式完成第一个任务:
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屋!