On Wed, Jun 06, 2012 at 11:02:46PM -0700, Sarah Auburn wrote: > Hi, > I am trying to get a summary of the counts of different variables for each > sample in a matrix of the form "m" below to generate an output as shown. > (Ultimately I want to generate a stacked barchart for each sample). I am only > able to get the "table" function to work on one sample (column) at a time. > Any help appreciated. > Thank you > Sarah > ? > a<-c("A", "A", "B", "B", "C", "A", "C", "D", "A", "D", "C", "A", "D", "C", > "A", "C") > m<-matrix(a, nrow=4) > m > ???? [,1] [,2] [,3] [,4] > [1,] "A"? "C"? "A"? "D" > [2,] "A"? "A"? "D"? "C" > [3,] "B"? "C"? "C"? "A" > [4,] "B"? "D"? "A"? "C" > > output needed (so that I can use the "barplot(t(output))" function): > A B C D > [,1] 2 2 0 0 > [,2] 1 0 2 1 > [,3] 2 0 1 1 > [,4] 1 0 2 1
Hi. Try the following. a<-c("A", "A", "B", "B", "C", "A", "C", "D", "A", "D", "C", "A", "D", "C", "A", "C") m<-matrix(a, nrow=4) tab <- function(x) { table(factor(x, levels=LETTERS[1:4])) } t(apply(m, 2, tab)) A B C D [1,] 2 2 0 0 [2,] 1 0 2 1 [3,] 2 0 1 1 [4,] 1 0 2 1 Factors are used to ensure that all the tables have the same length, even if some letters are missing. Hope this helps. Petr Savicky. ______________________________________________ R-help@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.