2

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")

enter image description here

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!

geoQuant
  • 95
  • 1
  • 1
  • 7

1 Answers1

2

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
sgibb
  • 25,396
  • 3
  • 68
  • 74
  • @JoshuaUlrich: You are right. I didn't recognize the unexpected (at least for me) behaviour of the 6th and 7th value (see your comment to the question). I will wait for an answer of the OP and eventually edit/remove my answer. – sgibb Mar 31 '14 at 20:55
  • Very cool! Thank you, I was unaware of the which.min function. I think I stated my problem incorrectly, but working with your solution has helped me figure out my problem – geoQuant Mar 31 '14 at 20:56
  • I was going to answer basically the same thing, but without hard-coding `4`: `function(x) NROW(x)-which.min(x)+1`. – Joshua Ulrich Mar 31 '14 at 20:58
  • @JoshuaUlrich: Thanks, that's even better. I changed my answer. – sgibb Mar 31 '14 at 20:59