[R] contingency table

Marc Schwartz marc_schwartz at me.com
Tue Dec 20 21:43:01 CET 2011


On Dec 20, 2011, at 12:36 PM, reena wrote:

> This is my list.
> obs1    obs2    exp1     exp2
> 
> 3           8          725      875
> 0           0           58        70
> 3           7          435      525
> 10         7          754      910
> 0           1          145     175
> 
> and i want result in contingency table as
> 
> obs       3                8
> exp    725          875
> 
> next table will be
> 
> obs    0         0
> exp   58       70
> 
> and so on... 


Hi,

It's not clear what you intend to do with the data after restructuring, but creating a list of the 2x2 tables from each row seems a reasonable first step.

Thus, if your data above is contained in a data frame 'DF':

> DF
  obs1 obs2 exp1 exp2
1    3    8  725  875
2    0    0   58   70
3    3    7  435  525
4   10    7  754  910
5    0    1  145  175


# Iterate over each row in DF, returning a 2x2 matrix from each

> lapply(seq(nrow(DF)), function(i) matrix(DF[i, ], 2, 2, byrow = TRUE))
[[1]]
     [,1] [,2]
[1,] 3    8   
[2,] 725  875 

[[2]]
     [,1] [,2]
[1,] 0    0   
[2,] 58   70  

[[3]]
     [,1] [,2]
[1,] 3    7   
[2,] 435  525 

[[4]]
     [,1] [,2]
[1,] 10   7   
[2,] 754  910 

[[5]]
     [,1] [,2]
[1,] 0    1   
[2,] 145  175 


This gives you a list of 5 2x2 matrices, one from each row in DF. See ?lapply, ?seq and ?matrix.

HTH,

Marc Schwartz



More information about the R-help mailing list