问题
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")
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")
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]
But then i fail at appending the new objects, as determined by the unique elements in v2:
new.elements <- v2[!v2 %in% v1]
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.
回答1:
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"
And then subset existing.list
and append it as follows
existing.list <- c(existing.list[v1 %in% v2],
setNames(vector("list", length(tmp)), tmp))
Result
existing.list
#$B
#NULL
#$C
#NULL
#$D
#NULL
回答2:
Are these what you are looking for?
intersect(v1, v2)
# [1] "B" "C"
setdiff(v2, v1)
# [1] "D"
来源:https://stackoverflow.com/questions/56027906/removing-and-appending-elemets-from-and-to-a-list-based-on-a-vector-overlap