Olga Lyashevska
2010-Aug-26 09:47 UTC
[R] frequency table for a list matching some conditions
Dear all, I have a list that contains 3 sublists( x1, x2, x3) mylist<-list(x1=c("A","A","A","B","C","Z","Y"),x2=c("D","D","E","E","F","Z","X"),x3=c("A","A","A","B","Y","Z")) mylist $x1 [1] "A" "A" "A" "B" "C" "Z" "Y" $x2 [1] "D" "D" "E" "E" "F" "Z" "X" $x3 [1] "A" "A" "A" "B" "Y" "Z" I also have another list, that contains some specific elements. newlist<-c("A","B","C","D","E","F") newlist [1] "A" "B" "C" "D" "E" "F" I want to match mylist[1], mylist[2], etc with newlist and I am looking for the following output: A B C D E F x1 3 1 1 NA NA NA x2 NA NA NA 2 2 1 x3 3 1 NA NA NA NA Any thoughts? Many thanks Olga
Dimitris Rizopoulos
2010-Aug-26 09:55 UTC
[R] frequency table for a list matching some conditions
one way is the following: mylist <- list(x1 = c("A","A","A","B","C","Z","Y"), x2 = c("D","D","E","E","F","Z","X"), x3 = c("A","A","A","B","Y","Z")) newlist <- c("A","B","C","D","E","F") tab <- t(sapply(mylist, function (x) table(factor(x, levels = newlist)))) tab[tab == 0] <- NA tab I hope it helps. Best, Dimitris On 8/26/2010 11:47 AM, Olga Lyashevska wrote:> Dear all, > > I have a list that contains 3 sublists( x1, x2, x3) > > mylist<-list(x1=c("A","A","A","B","C","Z","Y"),x2=c("D","D","E","E","F","Z","X"),x3=c("A","A","A","B","Y","Z")) > mylist > $x1 > [1] "A" "A" "A" "B" "C" "Z" "Y" > > $x2 > [1] "D" "D" "E" "E" "F" "Z" "X" > > $x3 > [1] "A" "A" "A" "B" "Y" "Z" > > I also have another list, that contains some specific elements. > newlist<-c("A","B","C","D","E","F") > newlist > [1] "A" "B" "C" "D" "E" "F" > > I want to match mylist[1], mylist[2], etc with newlist and I am looking for the following output: > > A B C D E F > x1 3 1 1 NA NA NA > x2 NA NA NA 2 2 1 > x3 3 1 NA NA NA NA > > Any thoughts? > > Many thanks > Olga > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Dimitris Rizopoulos Assistant Professor Department of Biostatistics Erasmus University Medical Center Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands Tel: +31/(0)10/7043478 Fax: +31/(0)10/7043014
Olga Lyashevska
2010-Aug-26 10:48 UTC
[R] frequency table for a list matching some conditions
Thanks Dimitris, It works nicely! Regards, Olga On Thu, 2010-08-26 at 11:55 +0200, Dimitris Rizopoulos wrote:> one way is the following: > > mylist <- list(x1 = c("A","A","A","B","C","Z","Y"), > x2 = c("D","D","E","E","F","Z","X"), > x3 = c("A","A","A","B","Y","Z")) > newlist <- c("A","B","C","D","E","F") > > > tab <- t(sapply(mylist, function (x) > table(factor(x, levels = newlist)))) > tab[tab == 0] <- NA > tab