[R] Newbie: 'table' output in columns rather than matrix
Marc Schwartz
marc_schwartz at comcast.net
Fri Sep 12 04:56:20 CEST 2008
on 09/11/2008 09:34 PM Matthew Pettis wrote:
> Hi,
>
> Coming to R from SAS...
Welcome!
> I have a data.frame A with 2 long factors "x" and "y". I want to get
> a count of the number of rows with each level of "x" and "y" jointly.
> 'table' seemed like it would work, but as I have many levels, the
> matrix output is pretty useless to me (and I don't care about zero
> values). How can I get output that looks like:
>
> A$x A$y Freq
> ------ ----- -------
> x1 y1 8
> x1 y3 10
> ...
>
> Thanks a ton,
> Matt
See ?as.data.frame.table
Example using the 'warpbreaks' dataset:
> str(warpbreaks)
'data.frame': 54 obs. of 3 variables:
$ breaks : num 26 30 54 25 70 52 51 26 67 18 ...
$ wool : Factor w/ 2 levels "A","B": 1 1 1 1 1 1 1 1 1 1 ...
$ tension: Factor w/ 3 levels "L","M","H": 1 1 1 1 1 1 1 1 1 2 ...
> with(warpbreaks, table(wool, tension))
tension
wool L M H
A 9 9 9
B 9 9 9
> as.data.frame(with(warpbreaks, table(wool, tension)))
wool tension Freq
1 A L 9
2 B L 9
3 A M 9
4 B M 9
5 A H 9
6 B H 9
So with your data:
as.data.frame(with(A, table(x, y)))
See ?with also, which enables you to specify the column names 'with[in]'
the environment of the data frame, so that you need not use the '$' syntax.
HTH,
Marc Schwartz
More information about the R-help
mailing list