简体   繁体   中英

how to access different aggregated columns of aggregated data frame r

I have

> df=data.frame(name=c(rep('a',5),rep('b',4)),Value=rnorm(9,30,1))
> a=aggregate(df$Value,list(df$name),function(x)c(summary(x),length(x),sd(x)))
> df
  name    Value
1    a 30.83432
2    a 30.59692
3    a 30.16761
4    a 29.75632
5    a 30.56168
6    b 27.54306
7    b 29.20575
8    b 30.59607
9    b 29.75491
> a
  Group.1     x.Min.  x.1st Qu.   x.Median     x.Mean  x.3rd Qu.     x.Max.       x.V7       x.V8
1       a 29.7600000 30.1700000 30.5600000 30.3800000 30.6000000 30.8300000  5.0000000  0.4244106
2       b 27.5400000 28.7900000 29.4800000 29.2700000 29.9700000 30.6000000  4.0000000  1.2884043

I want to use the mean for another function, but do not know how to access it. I cannot call the column out with a$x.Mean, as a only has 2 columns

> dim(a)
[1] 2 2
> colnames(a)
[1] "Group.1" "x"  

I do not want to save and then read it in, as the actual df is quite large.

Can anyone guide me to how I can access the different columns of an aggregated table. As an extra, is it also possible to rename each of the calculated fields as well

The answer is here: R: results from aggregate with multiple functions not usable in further calculations. WHY?

Once I aggregate, I convert to a list and then a data.frame

> as.data.frame(as.list(a))
  Group.1 x.Min. x.1st.Qu. x.Median x.Mean x.3rd.Qu. x.Max. x.V7      x.V8
1       a  29.76     30.17    30.56  30.38     30.60  30.83    5 0.4244106
2       b  27.54     28.79    29.48  29.27     29.97  30.60    4 1.2884043
> dim(as.data.frame(as.list(a)))
[1] 2 9
> 

You can access the x.Mean column by a$x[,4] . If you want to change the names of the columns for a use names(a) <- c("Name", "Value") . If you want to change the x.Mean, x.Min,... names, then use colnames(a$x) <- c("Min", "FQ",...) or if you only want to change one column use colnames(a$x)[1] <- "Min" . Note that since I changed the x name to Value in a that you would also need to change colnames(a$x) to colnames(a$Value) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM