-1

I'm trying to write a function using ddply package. I've read several solutions, but I couldn't figure it out how to tackle this issue in my case.

Rolling <- function(ID, RP){ 
 require(plyr)
 cn=colnames(ID)
 Rolling3M=ddply(ID, cn[2:(length(cn)-1)], transform, Rolling3M = as.numeric(filter(v3,c(1,rep(1,times=RP)),sides=1)))
 return(Rolling3M)
}

 v1=c("a","a","a","a","a","a","a","b","b","b","b","b","b")
 v2=c("c","c","c","d","d","d","d","c","c","c","d","d","d")
 v3=c(1:13)
 df = data.frame(v1,v2,v3)
 output=Rolling(df, 3)

I got this error message: Error: object 'RP' not found

I'd like to do the same as this would do:

output=ddply(df, .(v1,v2),transform, Rolling3M=as.numeric(filter(v3,c(1,rep(1,2)), sides=1)))
user1731038
  • 35
  • 1
  • 2
  • 6
  • 3
    How are you calling the function? Please give sample data to create a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – MrFlick Jul 28 '14 at 13:57
  • I get an error that also involves that arguments to `filter`, but it is for the first argument, "Freq", rather than the second. That makes more sense to me because I see nothing named "Freq". – IRTFM Jul 28 '14 at 17:04

1 Answers1

0

Have you looked at this question: Object not found error with ddply inside a function

Looks like it's a problem with variable scope based on the ddply function. There's some more info about it here from Hadley (author of plyr package) if you want to more details about it. Seems like it's problematic to fix this issue.

The top rated answer in the SO thread above uses do.call to get around the environment scoping issue, using it to call ddply. For your example, that would change the function to:

Rolling <- function(ID, RP){ 
    require(plyr)
    cn <- colnames(ID)
    Rolling3M <- do.call("ddply",list(ID, cn[2:(length(cn)-1)], transform, Rolling3M <- as.numeric(filter(c,c(1,rep(1,times = RP)),sides=1))))
    return(Rolling3M)
}

Which gives the output:

  a b c
1 1 0 5
2 2 0 6
3 3 1 7
4 4 1 8

Was that that output you would expect from the function? You didn't say in your question.

Credit to James for his answer in the SO thread linked above.

Community
  • 1
  • 1
syntonicC
  • 371
  • 3
  • 17