[R] Union of list elements

Liaw, Andy andy_liaw at merck.com
Fri Dec 17 19:19:28 CET 2004


All the ways of doing such things (that I know of) in R only work on atomic
objects, so one way to do it is, again, concatenate the vectors into one
string, then do the comparison:

> lst = list(c("a1", "a3", "a4"), c("a1", "a4", "a5"), c("a1", "a5", "a6"))
> lst.vec <- sapply(lst, paste, collapse=":")
> lst.vec
[1] "a1:a3:a4" "a1:a4:a5" "a1:a5:a6"
> x <- lst[[1]]
> paste(x, collapse=":") %in% lst.vec
[1] TRUE

Then you can "grow" the list by something like:

if (!paste(x, collapse=":") %in% lst.vec) lst <- c(lst, list(x))

[BTW, note that this only works if order matters; i.e., c("a1", "a3", "a4")
not equal to c("a4", "a3", "a1").]

HTH,
Andy

> From: Pat Meyer
> 
> Hi,
> 
> First of all, let me thank you all for replying so rapidly to 
> my first 
> question on this list. It was very very helpfull... and I'm 
> learning R 
> faster and faster.
> 
> I just encountered a second problem, which may also have a 
> simple solution.
> 
> Here it is:
> 
> In my program, a vector is a set of objects.
> 
> I was looking for a way to store these sets in a big object. 
> I chose to 
> store them in a list.
> 
> So now I have a list of vectors which looks as follows:
> 
> [[1]]
> [1] "a1" "a3" "a4"
> 
> [[2]]
> [1] "a1" "a4" "a5"
> 
> [[3]]
> [1] "a1" "a5" "a6"
> 
> Then comes a crucial step where I may have to add the vector 
> ("a3", "a1", 
> "a4") in this list.
> 
> But as you can see, this set is already present (at position 
> 1 of my list). 
> So it should not be added. If I do a systematic 
> concatenation, at the end, I 
> have a list with too many vectors (where some elements of my 
> list represent 
> the same set).
> 
> So what I would like to do is a type of Union, but I can't 
> find a way to do 
> it. Unions work only on vectors, and not a vector and a list 
> of vectors.
> 
> Can anyone help me with this?
> 
> I thank you very much in advance
> 
> Patrick
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list