Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting last n items in a time series

I want to select the last n items of a time series. I can use the [ operator, but I lose the time series attributes of the data:

data <- ts(1:10, frequency = 4, start = c(1959, 2))
data[(length(data)-4):length(data)] 

I've written a wrapper function to re-apply the time series attributes, but I was wondering if there was a more elegant way to do this?

lastN <- function(data,n) {
    out <- data[(length(data)-n+1):length(data)] 
    ts(out, end=end(data), frequency=frequency(data))
}
data
lastN(data,5)

Why doesn't the [ operator return a time series object?

like image 931
Zach Avatar asked Oct 11 '11 18:10

Zach


2 Answers

I suspect that this isn't what you are looking for, but you can use the usual extract ([) syntax with zoo objects:

library(zoo)
data_zoo <- as.zoo(data)
last_zoo <- data_zoo[(length(data_zoo)-4):length(data_zoo)]

Then, if you like, convert back to a ts object:

as.ts(last_zoo)
like image 159
Jason B Avatar answered Sep 23 '22 02:09

Jason B


[ does not return a ts object because data[c(1,5,6)] for example would not work. Instead there is the window() function:

window(data,start=tsp(data)[2]-4/frequency(data))

So a modification of your lastN function would be

tail.ts <- function(data,n) {
  data <- as.ts(data)
  window(data,start=tsp(data)[2]-(n-1)/frequency(data))
}

Then tail(data,5) will do what you want.

like image 39
Rob Hyndman Avatar answered Sep 19 '22 02:09

Rob Hyndman