[R] list matching

Marc Schwartz marc_schwartz at comcast.net
Sat Oct 6 22:12:58 CEST 2007


On Sat, 2007-10-06 at 19:49 +0000, Adrian Dusa wrote:
> Dear list,
> 
> Given a list of elements like:
> aa <- list(one=c("o", "n", "e"),
>                tea=c("t", "e", "a"),
>                thre=c("t", "h", "r", "e"))
> 
> Is there a function that returns the intersection between all?
> Both match() and intersect() only deal with two arguments, but sometimes I 
> have more.
> 
> Here, it should return "e" (or NA if none of the letters are common).
> 
> I have a solution to apply %in% multiple times (here two times, first between 
> the first two and then between the result and the third) but... perhaps there 
> is a better and quicker way.
> 
> Thanks in advance,
> Adrian


intersectList <- function(x) 
{
  res <- table(unlist(sapply(x, unique)))
  names(res[res == length(x)])
}


In the first line, I use unique() to ensure that if the same letter
appears more than once in the same list element, it is not included in
the result set in error, such as in 'L' here:


L <- list(a = c("a", "b", "b"), b = c("d", "b", "a"), c = c("d", "a"))

> L
$a
[1] "a" "b" "b"

$b
[1] "d" "b" "a"

$c
[1] "d" "a"


So:

> intersectList(aa)
[1] "e"

> intersectList(L)
[1] "a"


HTH,

Marc Schwartz



More information about the R-help mailing list