[R] finding common elements in a list

Patrick Burns pburns at pburns.seanet.com
Fri Apr 7 21:03:36 CEST 2006

Here is one solution:

 > all(unlist(lapply(foo, function(x) c(2,3) %in% x)))
[1] TRUE

This doesn't have the restriction of assuming that the components
of the list have unique elements, as the original solution does.

Patrick Burns
patrick at burns-stat.com
+44 (0)20 8525 0696
(home of S Poetry and "A Guide for the Unwilling S User")

Andy Bunn wrote:

>Suppose I have a list where I want to extract only the elements that occur
>in every component. For instance in the list foo I want to know that the
>numbers 2 and 3 occur in every component. The solution I have seems
>unnecessarily clunky. TIA, Andy
>    foo <- list(x = 1:10, y=2:11, z=1:3)
>    bar <-unlist(foo)
>    bartab <- table(bar)
>    as.numeric(names(bartab)[bartab==length(foo)])
>	[[alternative HTML version deleted]]
>R-help at stat.math.ethz.ch mailing list
>PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

More information about the R-help mailing list