[Solved] Multiple aggregation in R with 4 parameters


You could try something like this in data.table

data <- data.table(yourdataframe)

bar <- data[,.N,by=y]
foo <- data[x==1 & z==1,list(mean.t=mean(t,na.rm=T),median.t=median(t,na.rm=T)),by=y]
merge(bar[,list(y)],foo,by="y",all.x=T)

   y mean.t median.t
1: 1   12.5     12.5
2: 2     NA       NA
3: 3     NA       NA
4: 4     NA       NA

You probably could do the same in aggregate, but I am not sure you can do it in one easy step.

An answer to to an additional request in the comments…

bar <- data.table(expand.grid(y=unique(data$y),z=unique(data[z %in% c(1,2,3,4),z])))
foo <- data[x==1 & z %in% c(1,2,3,4),list(
  mean.t=mean(t,na.rm=T),
  median.t=median(t,na.rm=T),
  Q25.t=quantile(t,0.25,na.rm=T),
  Q75.t=quantile(t,0.75,na.rm=T)
  ),by=list(y,z)]
merge(bar[,list(y,z)],foo,by=c("y","z"),all.x=T)

    y z mean.t median.t Q25.t Q75.t
 1: 1 1   12.5     12.5 11.25 13.75
 2: 1 2     NA       NA    NA    NA
 3: 1 3     NA       NA    NA    NA
 4: 1 4     NA       NA    NA    NA
 5: 2 1     NA       NA    NA    NA
 6: 2 2     NA       NA    NA    NA
 7: 2 3     NA       NA    NA    NA
 8: 2 4     NA       NA    NA    NA
 9: 3 1     NA       NA    NA    NA
10: 3 2     NA       NA    NA    NA
11: 3 3     NA       NA    NA    NA
12: 3 4     NA       NA    NA    NA
13: 4 1     NA       NA    NA    NA
14: 4 2   18.0     18.0 18.00 18.00
15: 4 3   45.0     45.0 45.00 45.00
16: 4 4     NA       NA    NA    NA

11

solved Multiple aggregation in R with 4 parameters