Data window moving in time (t)

Asked

Viewed 106 times

4

I want to make a recursive prediction. I need each month (t) to move the data window of the last month forward in a period (monthly period, that is, t+1).

dados<-read.table("C:/Biomedica/Doença/evolmensal.txt", header=T, dec=",")
dados.ts <- ts(dados, start=c(1998,03), freq=12)
    periodo = window(dados.ts, start=c(1999,01),end=c(2007,12))
periodo

    stat=c(2008,01) 
dado_de_fora=window(dados.ts,start=stat)  

recurs.pred1=ts(0,start=stat,end=c(2014,10),frequency=12) 

Follow the looping:

    for (t in 1:(length(dado_de_fora))) {
  reg.recur1=arima(window(periodo,end=c(2007,11+t)),order=c(1,0,1))
  recurs.pred1[t]=predict(reg.recur1,n.ahead=1)$pred

The problem I’m facing is that when t equals 2 the window keeps taking only the period end=c(2007,12)that is, does not walk towards end=c(2008,01)and so on.

When I spin:

window(periodo,end=c(2007,11+3))

Should get as given end February 2008

2 answers

3

A possible solution without using the window, using indexers to pick up only a part of the time series (the [], if I have another name, let me know!)

prev <- se <- NULL
for (i in 0:12) {
dados.ts <- ts(AirPassengers[1:(24 + i)], start = start(AirPassengers), frequency = frequency(AirPassengers))
prev[i + 1] <- predict(arima(dados.ts, c(1,0,1)), 1)$pred
se[i + 1] <- predict(arima(dados.ts, c(1,0,1)), 1)$se
}
  • Thanks, I’ll try! It seems I got it, but I used window. I added the command 'extend=TRUE' inside the window.

2

When I spin:

window(periodo,end=c(2007,11+3))

Should get as given end February 2008

Answering this point of adding months:

To get what you want in this operation, you have to operate with dates. I’ll give an example with the packages xts and lubridate. First we need to turn your numbers into a date format.

library(xts)
end <- c(2007, 11) # vetor de números
end <- paste(end, collapse="-") # transforma em texto
end <- as.yearmon(end) # transforma em data (formato yearmon)

Now you can add up months:

end + 3/12
[1] "Fev 2008"

You can also return to the number format using the functions year and month (lubridate) to extract the numbers of the year and month:

library(lubridate)
end <- end + 3/12 # adicionamos 3 meses ao vetor end
end <- c(year(end), month(end)) # transformamos o vetor end em número novamente
end
[1] 2008    2

So you could work with something like that. Now, in your specific case, it’s easier to loop with a number index than with dates - as Rcoster put it - but it may be that another circumstance you actually need to deal with dates.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.