[R] Aggregate and cross tabulation

Jonathan Greenberg greenberg at ucdavis.edu
Wed Oct 28 01:32:22 CET 2009


R-helpers:

    I have a data frame containing 4 factor variables (let's say A,B,C, 
and D) and 1 numerical variable (N).  I would like to produce a 
cross-tabulated data frame in which A,B,C are individual columns, each 
factor of D is its own column, and the field is calculated as a given 
function of N (I would like to have two output data frames, one with the 
mean(N) and one with the sum(N), e.g.:

A,    B,    C,    D1,                                        D2,        
                                ...,        DM
A1   B1   C1   mean(N{A1,B1,C1,D1)})   mean(N{A1,B1,C1,D2)})            
    mean(N{A1,B1,C1,DM)})
A2   B1   C1   mean(N{A2,B1,C1,D1)})   mean(N{A2,B1,C1,D2)})            
    mean(N{A2,B1,C1,DM)})
etc...

I can mostly do this with aggregate, e.g.
output = aggregate(N,list(A,B,C,D),mean), but I can't get that last step 
of cross-tabulating the Ds to column headers.  table() and xtabs() 
appear to just count, rather than giving me access to sum() and mean().  
Any ideas?  Ideally I'd like to do this in a single step, as the 
aggregate output (above) produces a much larger data frame than a 
cross-tabulated output would (in my particular case).

--j

-- 

Jonathan A. Greenberg, PhD
Postdoctoral Scholar
Center for Spatial Technologies and Remote Sensing (CSTARS)
University of California, Davis
One Shields Avenue
The Barn, Room 250N
Davis, CA 95616
Phone: 415-763-5476
AIM: jgrn307, MSN: jgrn307 at hotmail.com, Gchat: jgrn307




More information about the R-help mailing list