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?
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)
[
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With