Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic column name label with cast

Tags:

r

reshape

When using reshape::cast is there a way to set the name of the resulting column?

Example:

library(reshape)
data(mtcars)
cast(mtcars, cyl + hp ~ .,mean)

   cyl  hp (all)
1    4  52     2
2    4  62     2
3    4  65     1
4    4  66     1
5    4  91     2

Instead of (all), I'd like to be able to set the name within the call to cast. Is this possible?

I know, I know, it's as if typing colnames(x)[3] <- "Foo" is too difficult, but it's time consuming if you have to do it frequently!

like image 361
Brandon Bertelsen Avatar asked Jul 05 '12 23:07

Brandon Bertelsen


3 Answers

Create a new wrapper that provides the facility you seek (which means I could not find an existing argument that would do it):

bcast <- function(... , agg.name =NA){ res <- cast(...)
             if(!is.na(agg.name)){ names(res)[length(res)] <- agg.name } 
             res}
bcast(mtcars, cyl + hp ~ . ,  fun.aggregate= mean, agg.name="test")

#--------
#Using carb as value column.  Use the value argument to cast to override this choice
#   cyl  hp test
1    4  52    2
2    4  62    2
3    4  65    1
4    4  66    1
5    4  91    2
6    4  93    1
7    4  95    2
snipped output....
like image 89
IRTFM Avatar answered Nov 17 '22 12:11

IRTFM


For a simple reshape as in your example, you could simply use aggregate in base R, which does what you want, without the need to specify the column name:

aggregate(carb~cyl+hp, mtcars, FUN=mean)

   cyl  hp carb
1    4  52    2
2    4  62    2
3    4  65    1
4    4  66    1
5    4  91    2
.....

Or on all of the columns:

aggregate(.~cyl+hp, mtcars, FUN=mean)

   cyl  hp      mpg     disp     drat       wt     qsec        vs        am     gear carb
1    4  52 30.40000  75.7000 4.930000 1.615000 18.52000 1.0000000 1.0000000 4.000000    2
2    4  62 24.40000 146.7000 3.690000 3.190000 20.00000 1.0000000 0.0000000 4.000000    2
3    4  65 33.90000  71.1000 4.220000 1.835000 19.90000 1.0000000 1.0000000 4.000000    1
4    4  66 29.85000  78.8500 4.080000 2.067500 19.18500 1.0000000 1.0000000 4.000000    1
5    4  91 26.00000 120.3000 4.430000 2.140000 16.70000 0.0000000 1.0000000 5.000000    2
 .....
like image 35
Andrie Avatar answered Nov 17 '22 11:11

Andrie


In reshape::cast it is not possible to set the default column name, but in reshape2::dcast it is (which you could use anyway, because it is way faster). Using your example:

dcast (mtcars, cyl + hp ~ "colname", mean)
like image 1
themeo Avatar answered Nov 17 '22 11:11

themeo