Thank you for all your help! I am working with time-series data and trying to identify the count at which an observation occurred, while working with the rollapply function in R. To clarify, here is some code:
# Sample Data
dates <- c("2014-01-01","2014-01-02","2014-01-03","2014-01-04","2014-01-05",
"2014-01-06","2014-01-07","2014-01-08","2014-01-09","2014-01-10")
data <- c(20,12,31,26,22,22,31,10,22,23)
xts.object <- as.xts(data,as.Date(dates))
# Apply 4-Day Min
rollMin <- rollapply(xts.object,4,min)
xts.object2 <- cbind(xts.object,rollMin)
# Desired Output
desiredOutput <- c(NA,NA,NA,3,4,1,2,1,2,3)
xts.object3 <- cbind(xts.object2,desiredOutput)
colnames(xts.object3) <- c("data","rollMin","desiredOutput")
The first 3 observations of desiredOutput is NA's because the window size selected for the rollapply function is set to 4. On the 4th observation, the min was 12 and that has been true for 3 days, therefore the desiredOutput displays 3 on 2014-01-04.
Thanks, again!
You can use rollapply
here as well. which.min
will return the index of the minimal value. To get the range of days you have to reduce the window size (+ one, because in R indices starting at 1) by the index.
rollapply(xts.object,4,function(x)NROW(x)-which.min(x)+1)
# [,1]
#2014-01-01 NA
#2014-01-02 NA
#2014-01-03 NA
#2014-01-04 3
#2014-01-05 4
#2014-01-06 2
#2014-01-07 3
#2014-01-08 1
#2014-01-09 2
#2014-01-10 3