0

I have a panel dataset that is broken down into 4 "events". For each event I would like a moving 48 period average. However, I need the moving average to reset at the next event.

I have the following moving average code that is getting me the MA:

MAV <- function(x,n=48) {filter(data.crunch$THI.lag,rep(1/n,n), sides=1)} #Need to set sides=1
data.crunch$MAV <- MAV(data.crunch$THI.lag)

However, I need to add something to make it reset. I've tried a by statement, but it's not working:

MAV <- function(x,n=48) {filter(data.crunch$THI.lag,rep(1/n,n), sides=1)} #Need to set sides=1
data.crunch$MAV <- MAV(data.crunch$THI.lag, by=c('event_name'))

Any help would be greatly appreciated!

Kohlbrr
  • 3,861
  • 1
  • 21
  • 24
Luna
  • 39
  • 1
  • 5
  • Read this about how to ask a question on SO's R tag: http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – G. Grothendieck Apr 09 '14 at 16:00
  • try split() by event, use lapply with your MAV function, and unsplit to rejoin to a single dataframe – Miff Apr 09 '14 at 16:17
  • @Miff It would be easier to use one of the many functions that implement the "split-apply-combine" approach. – Roland Apr 09 '14 at 16:20
  • OK, thanks for your comments, I was not overly successful with split so I ended up using a workaround. – Luna Apr 15 '14 at 12:37

0 Answers0