How do I pass variables to a custom function in ddply?

Viewed 6955

Consider the following data:

d = data.frame(
    experiment = as.factor(c("foo", "foo", "foo", "bar", "bar")),
    si = runif(5),
    ti = runif(5)
)

I would like to perform a correlation test for si and ti, for each experiment factor level. So I thought I'd run:

ddply(d, .(experiment), cor.test)

But how do I pass the values of si and ti to the cor.test call? I tried this:

> ddply(d, .(experiment), cor.test, x = si, y = ti)
Error in .fun(piece, ...) : object 'si' not found
> ddply(d, .(experiment), cor.test, si, ti)
Error in match.arg(alternative) : 
  'arg' must be NULL or a character vector

Is there anything obvious I'm missing? The plyr documentation does not include any example for me. Most commands I see only involve summarize as the function call, but doing the usual things I was used to doing from summarize don't work, as can be seen above.

2 Answers
Related