# [R] Union of list elements

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

```> From: Gabor Grothendieck
>
> Pat Meyer <paterijk <at> hotmail.com> writes:
>
> :
> : 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.
>
> L <- list(c("a1","a3","a4"), c("a1","a4","a5"), c("a1","a5","a6"))
> newentry <- c("a3", "a1", "a4")
> if (!any(sapply(L, setequal, newentry))) L <- c(L, list(newentry))

Cool, Gabor!  This works even if the sets have the same elements in
different orders.  Much better than what I had.

Best,
Andy

> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help