Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

aggregate - Multiple aggregation in R with 4 parameters

I have four vectors (columns)

 x y z  t
 1 1 1 10
 1 1 1 15
 2 4 1 14
 2 3 1 15
 2 2 1 17
 2 1 2 19
 1 4 2 18
 1 4 2 NA
 2 2 2 45
 3 3 2 NA
 3 1 3 59
 4 3 3 23
 1 4 3 45
 4 4 4 74
 2 1 4 86

How can I calculate mean and median of vector t, for each value of vector y (from 1 to 4) where x=1, z=1, using aggregate function in R?

It was discussed how to do it with 3 parameters (Multiple Aggregation in R) but it`s a little unclear how to do it with 4 parameters.

Thank you.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...