[R-sig-teaching] Creating table from data.frame

Douglas Bates bates at stat.wisc.edu
Wed May 5 18:12:14 CEST 2010


On Wed, May 5, 2010 at 10:30 AM, Byungchul Cha <cha at muhlenberg.edu> wrote:

> I am a relatively novice in R and I need some help.

> I want to create a two-way table from a data given as a data.frame, which looks like this:

>> x
>   group status gender count
> 1      1     s1     g1   890
> 2      2     s1     g2   969
> 3      3     s2     g1   340
> 4      4     s2     g2   403
> 5      5     s3     g1  2897
> 6      6     s3     g2  3321
> 7      7     s4     g1   249
> 8      8     s4     g2   383
> 9      9     s5     g1   306
> 10    10     s5     g2   366
> 11    11     s6     g1   160
> 12    12     s6     g2   137
>
> I would like a two way table, which would look like
>
> status    men    women
> s1    890    969
> s2    340    403
> s3    2897    3321
> ...
>
> How do I do this in a relatively efficient way? Thanks.

Look up the documentation for xtabs, say by typing

?xtabs

in R.  What you want is

xtabs(count ~ status + gender, x)




More information about the R-sig-teaching mailing list