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

peter dalgaard pdalgd at gmail.com
Thu Jul 22 17:05:20 CEST 2010


On Jul 22, 2010, at 4:00 PM, Liat wrote:

> 
> Hi guys,
> I hope you can help me with this.
> Here is the problem:
> I have some data (myData) that looks similar to this:
> 
>     [,1] [,2] [,3] [,4]
> [1,] "A"  "A"  "B"  "B" 
> [2,] "B"  "B"  "B"  "B" 
> [3,] "C"  "C"  "C"  "C" 
> 
> When I build a contingency table for the first and second row using:
> tb <- table(myData[1,  ], myData[2,  ], useNA="ifany")
> I get:
>  B
>  A 2
>  B 2
> But - I would like to also see "C" there (with a zero).
> Actually, I would like to give a list of n characters that would be used to
> build an n*n table and the data for this table should then come from myData
> (and if there are characters in my list that do not appear in the data at
> all I would like to see a zero row or a zero column).
> Is that possible to do?
> What would be the simplest way?
> Many many thanks!!!
> Liat.

Just convert each character vector to a factor with the appropriate level set, as in

table(factor(myData[1,  ], levels=c("A","B","C")))

> -- 
> View this message in context: http://r.789695.n4.nabble.com/how-to-force-a-table-to-be-square-tp2298707p2298707.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.

-- 
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list