[R] apply and table

arun smartpink111 at yahoo.com
Sun May 19 20:04:04 CEST 2013


Hi,
May be this helps:
lev1<- unique(as.vector(z))
lapply(lapply(as.data.frame(z),factor,levels=lev1),table,lev1)


#$V1
 #  
  #  A B C
  #A 1 1 0
  #B 0 0 1
  #C 0 0 0
#
#$V2
 #  
  #  A B C
  #A 0 0 0
  #B 1 0 0
  #C 0 1 1
#
#$V3
 #  
  #  A B C
  #A 1 0 0
  #B 0 1 0
  #C 0 0 1

#or
library(plyr)

 llply(alply(z,2,factor,levels=lev1),table,lev1)
#$`1`
 #  lev1
  #  A B C
  #A 1 1 0
  #B 0 0 1
  #C 0 0 0
#
#$`2`
 #  lev1
  #  A B C
  #A 0 0 0
  #B 1 0 0
  #C 0 1 1
#
#$`3`
 #  lev1
  #  A B C
  #A 1 0 0
  #B 0 1 0
  #C 0 0 1



A.K.


----- Original Message -----
From: Jinsong Zhao <jszhao at yeah.net>
To: R help <r-help at r-project.org>
Cc: 
Sent: Sunday, May 19, 2013 10:22 AM
Subject: [R] apply and table

Hi there,

I have the following code:

z <- matrix(c("A", "A", "B", "B", "C", "C", "A", "B", "C"), ncol = 3)
apply(z, 2, table, c("A", "B", "C"))

which give correct results.

However, the following code:

apply(z[,1,drop=FALSE], 2, table, c("A", "B", "C"))

which does not give what I expect. I have been thought it should give 
the same result as:

apply(z, 2, table, c("A", "B", "C"))[[1]]

What's the difference? Does apply not apply to column vector?

Another question: how to output the table in squared matrix (or data 
frame)? For example:

> table(c("C", "B", "B"), c("A", "B", "C"))

     A B C
   B 0 1 1
   C 1 0 0

I hope to get the result something like:

     A B C
   A 0 0 0
   B 0 1 1
   C 1 0 0

Is there a way that can output that?

Any suggestions will be really appreciated. Thanks in advance.

Regards,
Jinsong

______________________________________________
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.




More information about the R-help mailing list