[R] how to force a table to be square?

William Dunlap wdunlap at tibco.com
Thu Jul 22 18:27:16 CEST 2010


> -----Original Message-----
> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Liat
> Sent: Thursday, July 22, 2010 8:41 AM
> To: r-help at r-project.org
> Subject: Re: [R] how to force a table to be square?
> 
> 
> Thanks Peter!
> that worked, and was so easy. LOL.
> I tried playing with factor and levels before I wrote here, 
> but obviously I
> didn't do it right.

Perhaps you expected to be able to make a matrix, m, of
factor data so that all columns would share the same levels
and you wouldn't have to call factor(levels=...) on each
column when you called table.  That might be a reasonable
expectation, but matrix(factorData) converts factorData to
character data before making a matrix out of it.  E.g.,

  > m <- matrix(factor(LETTERS[rep(1:4,1:4)]), ncol=2)
  > table(m[,1], m[,2])
     
      C D
    A 1 0
    B 0 2
    C 0 2
  > str(m)
   chr [1:5, 1:2] "A" "B" "B" "C" "C" "C" "D" "D" "D" "D"

Storing the data in a data.frame and assigning the same
levels to each column makes the calls to table simpler:
  > d <- data.frame(m)
  > d[] <- lapply(d, factor, levels=sort(unique(as.vector(m))))
  > table(d[,1], d[,2])
   
      A B C D
    A 0 0 1 0
    B 0 0 0 2
    C 0 0 0 2
    D 0 0 0 0

You can also use a back door method of making a matrix
from your factor such that the levels remain, but I don't
know if this is sanctioned or an accident of implementation:

  > f <- factor(LETTERS[rep(1:4,1:4)])
  > dim(f)<-c(5,2)
  > table(f[,1], f[,2])
     
      A B C D
    A 0 0 1 0
    B 0 0 0 2
    C 0 0 0 2
    D 0 0 0 0

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com  

> Thanks again,
> Liat.
> -- 
> View this message in context: 
> http://r.789695.n4.nabble.com/how-to-force-a-table-to-be-squar
e-tp2298707p2298875.html
> Sent from the R help mailing list archive at Nabble.com.
> 
> ______________________________________________
> 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