0

cast, from the reshape2 package, can handle a bunch of functions if passed directly in the call. For example:

library(reshape2)

d <- data.frame(variable="variable",value=rnorm(100))
cast(d, variable ~ ., c(mean,sd,max,min))

But, this doesn't work if you try to build the list of functions before hand. For example:

summary.fun <- c(mean,sd,max,min)
cast(d, variable ~., summary.fun) 

I looked at the code for cast that deals with this particular behaviour and, to be honest, I have no idea what it's doing:

if (length(fun.aggregate) > 1) 
        fun.aggregate <- do.call(funstofun, as.list(match.call()[[4]])[-1])

Is there a way to pass a premade list of functions as a variable to cast()?

Brandon Bertelsen
  • 43,807
  • 34
  • 160
  • 255

1 Answers1

4

Your function has to use an input argument. The function cast automatically passes the values as the first argument to the function. Furthermore, you have to tell R that summary.fun is a function using <- function().

summary.fun <- function(x) list(mean(x), sd(x), max(x), min(x))

Try this function with cast.

library(reshape)

d <- data.frame(variable="variable",value=rnorm(100))

cast(d, variable ~ ., summary.fun)

As @handley pointed out, this does not work with the cast function from the reshape2 package. You should have a look at dcast and acast.

Sven Hohenstein
  • 80,497
  • 17
  • 145
  • 168