[R] xtabs() of proportions, and naming a dimension (not a row)
Jeff Brown
dopethatwantscash at yahoo.com
Mon Apr 19 01:50:07 CEST 2010
Hi,
xtabs() creates a table of counts. I want a table of proportions -- that
is, I want to divide every vector (along a particular dimension) by its sum.
The tiny example below does that. The call to xtabs() creates a matrix "A"
with dimensions ("x1","x2","y"). I transform "A" using aperm() and aaply()
to get the matrix "B". The problem: "B" has dimensions (<No name>, "x2",
"x1"). How can I give (back) the name "y" to the dimension with no name in
the matrix "B"? (Unless I misunderstand something, dimnames() won't do it
-- that lets me name the rows in a given dimension, but not the dimension
itself.)
> df <- data.frame (
+ x1 = ceiling( runif( 20 ) * 3 ),
+ x2 = ceiling( runif( 20 ) * 2 ),
+ y = round( runif( 20 ) )
+ )
>
> attach( df )
> ( A <- xtabs( ~ y + x1 + x2 ) )
, , x2 = 1
x1
y 1 2 3
0 2 3 2
1 0 2 0
, , x2 = 2
x1
y 1 2 3
0 3 2 2
1 0 3 1
> detach(df)
> ( B <- aperm( aaply( A, 2:3, function (row) row / sum(row) ), c(3,1,2) ) )
, , x2 = 1
x1
1 2 3
0 1 0.6 1
1 0 0.4 0
, , x2 = 2
x1
1 2 3
0 1 0.4 0.6666667
1 0 0.6 0.3333333
> dimnames(B)
[[1]] # This is the line that's bothering me.
[1] "0" "1"
$x1
[1] "1" "2" "3"
$x2
[1] "1" "2"
If there's an easier way to get xtabs() to provide proportions instead of
counts, I'd like to know that, too. But whether there is or is not, I'd
like to know how to name a dimension.
Thanks a lot,
Jeff
--
View this message in context: http://n4.nabble.com/xtabs-of-proportions-and-naming-a-dimension-not-a-row-tp2015261p2015261.html
Sent from the R help mailing list archive at Nabble.com.
More information about the R-help
mailing list