How to do a moving MAX based on some rule in a data frame?
> days=Sys.Date()-1:70
> price=abs(rnorm(70))
> regular=rep(c(0,0,0,0,1,0,1,0,0,1),c(7,7,7,7,7,7,7,7,7,7))
> y=data.frame(cbind(days,price,regular))
y is like
days price regular 1 14990 0.16149463 0 2 14989 1.69519358 0 3 14988 1.57821998 0 4 1开发者_运维问答4987 0.47614311 0 5 14986 0.87016180 0 6 14985 2.55679229 0 7 14984 0.89753533 0the output I want: have another column appended to y, whose value is the max price in the recent 2 regular weeks. So if the current row is today, then get the max price of the past 14 days (including today) if the last 2 week are regular weeks, if one of the last 2 weeks is not regular week, then I need to go back further to find the max price, as I need the max price for the last 2 regular weeks. How can I do that? Or I have to use loop/if to do it?
BTW, why the days is like 14990,14989, after cbind(days,price,regular)? before the cbind, days is like the format "2010-12-23".
Assuming that a day is regular if regular == 1, for each row i we consider the rows 1 to i, remove the non-regular rows and return NA if there are no rows left or return the largest of the last 14 otherwise.
y <- data.frame(days, price, regular)
y$max <- sapply(1:nrow(y), function(i) with(subset(y[1:i, ], regular == 1),
if (length(regular) == 0) NA else max(tail(price, 14))))
精彩评论