[R] finding common elements in a list

Gabor Grothendieck ggrothendieck at gmail.com
Sun Apr 9 04:30:24 CEST 2006

I guess I am coming a bit late to this but here is a one-line zoo solution.
The lapply creates a zoo object from each foo component with the constant
value 1 and the contents as the times of that object.    Merging the objects
together using cbind gives columns of 1s and NAs and removing the NAs
leaves a zoo object at only the intersection of times, which we then extract.

time(na.omit(do.call(cbind, lapply(foo, zoo, x = 1))))  # 2, 3

On 4/8/06, Andy Bunn <abunn at nova.whrc.org> wrote:
> > The original post is ambiguous: do you want to find the intersection or do
> > you want to find whether a prespecified set is in the
> > intersection? Patrick
> > provided you an answer to the latter while you provided an answer to the
> > former. Actually, I thought using table as you did (mod the need for no
> > replicates) was clever. A more direct but I think considerably slower
> > approach would be to use intersect() in a loop:
> >
> > inall<-intersect(foo[[1]],foo[[,2]])
> > for(i in seq(3, to=length(foo))inall<-intersect(inall,foo[[i]])
> >
> > I suspect you already thought of this and rejected it. Other than
> > transparency, I think the only advantage it has is that it will work for
> > something other than lists of numerics, e.g. it will work for lists of
> > factors, which the table() solution would not.
> Indeed, the first post was ambiguous. I was after the type of solution that I posted: the intersection rather than a prespecified set. Given that, I suppose my use of table is satisfactory.
> Thanks Patrick and Bert.
> -Andy
> ______________________________________________
> 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