[R] Reshape with multiple aggregate functions

David Winsemius dwinsemius at comcast.net
Wed Jan 18 15:44:21 CET 2012


On Jan 18, 2012, at 4:06 AM, pengcafe wrote:

> I have a data frame and I would like to reshape it to wide format  
> while at
> the same time applying different aggregate functions to each column  
> AND at
> times multiple aggregate functions:
>
> test1 = data.frame(
>        id = c(rep('101',8),rep('102',8)),
>        phase  = rep(c('D','D','L','L'),4),
>        day = rep(c('1','1','1','1','2','2','2','2'),2),
>        col1 = c(rep(1,8),rep(2,8)),
>        col2 = c(runif(8,min=0,max=1),runif(8,min=0,max=10))
>        )
>
> In this example, I would like to end up with 2 rows (for the 2 ids)  
> and
> different columns for phase-day. Values of col1 should just be  
> summed and
> for col 2 there should be a column with the mean AND one with standard
> deviation for each phase-day combination.
>
> Obviously the real data have much more number of columns therefore I  
> guess I
> will need to provide a list of functions?

You should do the reshaping part and the aggregation parts separately  
and then merge the two (or three?) results on "id"

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list