[R] average and median values for each of the class

Berend Hasselman bhh at xs4all.nl
Sun Apr 27 14:33:48 CEST 2014


On 27-04-2014, at 11:01, Berend Hasselman <bhh at xs4all.nl> wrote:

> 
> On 27-04-2014, at 02:37, Nico Met <nicomet80 at gmail.com> wrote:
> 
>> Dear all,
>> 
>> I have a matrix (dimension, 16 x 12) where  2nd column represents class
>> (1,1,1,1,1,2,2,2, etc) information. I want to estimate average  and median
>> values for each of the class and add this information as a row at end of
>> the each classes.
>> …...
>> 
>> And same will be for other classes.
> 
> ……
> For each “class” (group would ba better name) you must append something different e.g. the “class”-number.
> 
> Try this:
> 
> library(plyr)
> g <- function(dat) { 
>    avg <- as.data.frame(aggregate(dat[,2:dim(dat)[2]], dat["class"], function(x) mean(x,na.rm=T)) )
>    med <- as.data.frame(aggregate(dat[,2:dim(dat)[2]], dat["class"], function(x) median(x,na.rm=T)) )   
>    z <- rbind(dat,avg,med) 
>    z
> }
> DAT1 <- ddply(dat,.(class),.fun=g)    
> rownames(DAT1) <- do.call(c,lapply(split(dat,dat["class"]),
>                                        FUN=function(x) c(rownames(x),paste0("Avg",x[,"class"][1]),paste0("Med",x[,"class"][1]))))
> DAT1
> 
> Convoluted but it works. Maybe someone else can come up with something shorter and more elegant.

Or something like this if you don’t want to use package plyr

g <- function(dat) { 
    avg <- as.data.frame(aggregate(dat[,2:dim(dat)[2]], dat["class"], function(x) mean(x,na.rm=T)) )
    med <- as.data.frame(aggregate(dat[,2:dim(dat)[2]], dat["class"], function(x) median(x,na.rm=T)) )   
    z <- rbind(dat,avg,med)  
    rownames(z) <- c(rownames(dat),paste0("Avg",dat[,"class"][1]),paste0("Med",dat[,"class"][1]))   
    print(z)
    z
} 

D <- lapply(split(dat,dat["class"]),FUN=g)
DAT2 <- do.call(rbind, lapply(D, data.frame)) 
# alternatively         
# DAT2 <- do.call(rbind, lapply(D,FUN=function(x) x )) 
rownames(DAT2) <- sub("[0-9]+\\.","",rownames(DAT2))
DAT2


Berend




More information about the R-help mailing list