[R] Normalising and pivoting tables

Wolfram Fischer - Z/I/M wolfram at fischer-zim.ch
Fri Jun 14 17:59:09 CEST 2002


I wanted to normalise table m1 into m2
and then get m1 back from m2. I did:

m1 <- matrix( 11:16, 3, 2, byrow=T )
rownames(m1) <- letters[1:3]
colnames(m1) <- toupper( letters[1:2] )
#-> m1
#      A  B
#   a 11 12
#   b 13 14
#   c 15 16
  
val <- as.vector(m1)
m2.index <- expand.grid( f1 = rownames(m1), f2 = colnames(m1) )
m2 <- cbind( m2.index, val )
#-> m2
#    f1 f2 val
#  1  a  A  11
#  2  b  A  13
#  3  c  A  15
#  4  a  B  12
#  5  b  B  14
#  6  c  B  16

m1.from.m2 <- matrix( m2$val, nlevels(m2$f1), nlevels(m2$f2) )
rownames(m1.from.m2) <- levels(m2$f1)
colnames(m1.from.m2) <- levels(m2$f2)
#-> m1.from.m2
#      A  B
#   a 11 12
#   b 13 14
#   c 15 16

m3 <- m2[c(1:2,4:6),]
#-> m3
#    f1 f2 val
#  1  a  A  11
#  2  b  A  13
#  3  a  B  12
#  4  b  B  14
#  5  c  B  16

m1.from.m3 <- ???


My questions:
- Is there a better/other way to get m2 from m1?
- Is there a better/other way to get m1.2 from m2?
- How to get m1.3 from m3 which would be m1.2 with NA instead of 15?


Thanks. Wolfram Fischer
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list