[BioC] problem about set operation and computation after split
Steve Lianoglou
mailinglist.honeypot at gmail.com
Thu Jun 7 16:36:15 CEST 2012
Hi,
Your questions aren't bioconductor/bioinformatics related, and should
really go to R-help.
Still, I'll offer one suggestion -- for more help, please repost the
question to r-help:
On Thu, Jun 7, 2012 at 4:36 AM, bestbird7788 [guest]
<guest at bioconductor.org> wrote:
>
> hi,
> I met some problems in R, please help me.
> 1. How to do a intersect operation among several groups in one list, without a loop statement? (I think It may be a list)
> create data:
> myData <- data.frame(product = c(1,2,3,1,2,3,1,2,2), year=c(2009,2009,2009,2010,2010,2010,2011,2011,2011),value=c(1104,608,606,1504,508,1312,900,1100,800))
> mySplit<- split(myData,myData$year)
> mySplit
> $`2009`
> product year value
> 1 1 2009 1104
> 2 2 2009 608
> 3 3 2009 606
>
> $`2010`
> product year value
> 4 1 2010 1504
> 5 2 2010 508
> 6 3 2010 1312
>
> $`2011`
> product year value
> 7 1 2011 900
> 8 2 2011 1100
> 9 2 2011 800
> I want to get intersection of product between every year. I know the basic is:
> intersect(intersect(mySplit[[1]]$product, mySplit[[2]]$product),mySplit[[3]]$product)
> this will give the correct answer:
> [1] 1 2
> above code lacks reusability, so It should use a for loop:
> myIntersect<-mySplit[[1]]$product
> for (i in 1:length(mySplit)-1){
> myIntersect<-intersect(myIntersect,mySplit[[i+1]]$product)
> }
> It's correct too, but stll too complex, so my question is:
> Can I do the same thing just use another similar intersect function (without for/repeat/while).
> What's this simple function's name ?
I think your for loop is "fine", but if you want a more functional way
of doing it, you could do:
myi <- Reduce(intersect, lapply(mySplit, '[[', 'product'))
-steve
--
Steve Lianoglou
Graduate Student: Computational Systems Biology
| Memorial Sloan-Kettering Cancer Center
| Weill Medical College of Cornell University
Contact Info: http://cbio.mskcc.org/~lianos/contact
More information about the Bioconductor
mailing list