[R] Make a table using data with frequency

Marc Schwartz marc_schwartz at me.com
Wed Feb 10 21:12:47 CET 2010


On Feb 10, 2010, at 2:02 PM, Soyeon Kim wrote:

> Dear All,
> 
> What I want is change following data
>> data
>  alc status age freq
> 1   0      0   0  408
> 2   1      0   0   64
> 3   0      1   0   26
> 4   1      1   0   30
> 5   0      0   1  258
> 6   1      0   1   45
> 7   0      1   1   78
> 8   1      1   1   66
> 
> To this table.
> 
> 	age =0		
> 		alc	
> 		0	1
> status       0	408	64
> 	1	26	30
> 	
>               age =1		
> 		alc	
> 		0	1
> status       0	258	45
> 	1	78	66
> 
> How can I do that?
> 
> Thanks,


See ?xtabs

With your data in a data frame called 'DF':

> DF
  alc status age freq
1   0      0   0  408
2   1      0   0   64
3   0      1   0   26
4   1      1   0   30
5   0      0   1  258
6   1      0   1   45
7   0      1   1   78
8   1      1   1   66


> xtabs(freq ~ status + alc + age, data = DF)
, , age = 0

      alc
status   0   1
     0 408  64
     1  26  30

, , age = 1

      alc
status   0   1
     0 258  45
     1  78  66


and you can reverse the process by using as.data.frame.table():

> as.data.frame.table(xtabs(freq ~ status + alc + age, data = DF))
  status alc age Freq
1      0   0   0  408
2      1   0   0   26
3      0   1   0   64
4      1   1   0   30
5      0   0   1  258
6      1   0   1   78
7      0   1   1   45
8      1   1   1   66


HTH,

Marc Schwartz



More information about the R-help mailing list