Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using aggregate() on data.frame objects

Tags:

r

aggregate

Why aggregate() doesn't work here?

> aggregate(cbind(var1 = 1:10, var2 = 101:110), 
      by=list(range=cut(1:10, breaks=c(2,4,8,10))), 
      FUN = function(x) 
        { 
        c(obs=length(x[, "var2"]), avg=mean(x[, "var2"]), sd=dev(x[, "var2"])) 
        })

Error in x[, "var2"] (from #1) : incorrect number of dimensions

> cbind(var1 = 1:10, var2 = 101:110)[, "var2"]
 [1] 101 102 103 104 105 106 107 108 109 110

UPDATE

Returned aggregate() values after running the correct version:

> r = aggregate(data.frame(var1 = 1:10, var2 = 101:110), by=list(range=cut(1:10, breaks=c(2,4,8,10))), FUN = function(x) { c(obs=length(x), avg=mean(x), sd=sd(x)) })
> class(r)
[1] "data.frame"
> dim(r)
[1] 3 3
> r[,1]
[1] (2,4]  (4,8]  (8,10]
Levels: (2,4] (4,8] (8,10]
> r[,2]
     obs avg       sd
[1,]   2 3.5 0.707107
[2,]   4 6.5 1.290994
[3,]   2 9.5 0.707107
> r[,3]
     obs   avg       sd
[1,]   2 103.5 0.707107
[2,]   4 106.5 1.290994
[3,]   2 109.5 0.707107
> class(r[,2])
[1] "matrix"
> class(r[,3])
[1] "matrix"
like image 521
Robert Kubrick Avatar asked Apr 27 '15 19:04

Robert Kubrick


2 Answers

Supply a dataframe and understand that aggregate passes only column vectors so using x[ , "colname"] is doomed because "x" is not a dataframe:

 aggregate(data.frame(var1 = 1:10, var2 = 101:110), 
       by=list(range=cut(1:10, breaks=c(2,4,8,10))), 
       FUN = function(x) 
         { 
         c(obs=length(x), avg=mean(x), sd=sd(x)) 
         })
#------------
   range  var1.obs  var1.avg   var1.sd    var2.obs    var2.avg     var2.sd
1  (2,4] 2.0000000 3.5000000 0.7071068   2.0000000 103.5000000   0.7071068
2  (4,8] 4.0000000 6.5000000 1.2909944   4.0000000 106.5000000   1.2909944
3 (8,10] 2.0000000 9.5000000 0.7071068   2.0000000 109.5000000   0.7071068
like image 147
IRTFM Avatar answered Nov 12 '22 13:11

IRTFM


That's because aggregate doesn't pass data.frames to its FUN= argument. It passes the vector of observations. Also, [, "name"] indexing doesn't work with matrices. Make sure you pass in a data.frame and not a matrix as in your example. Perhaps you want the by function instead

by(data.frame(var1 = 1:10, var2 = 101:110), 
    list(range=cut(1:10, breaks=c(2,4,8,10))), 
    FUN = function(x) { c(obs=length(x[, "var2"]), avg=mean(x[, "var2"]), sd=sd(x[, "var2"])) })
like image 20
MrFlick Avatar answered Nov 12 '22 14:11

MrFlick