Generating a time series time variable in R

I am a new user of R. I have a temporary serial data set and although I found ways to lag time series of data in R, I did not find a way to create lagging cross-section variables of the time series so that I could use them in my analysis.

+4
source share
2 answers

Here you can use the lag() function with zoo (and panel series data):

 > library(plm) > library(zoo) > data("Produc") > dnow <- pdata.frame(Produc) > x.Date <- as.Date(paste(rownames(t(as.matrix(dnow$pcap))), "-01-01", sep="")) > x <- zoo(t(as.matrix(dnow$pcap)), x.Date) > x[1:3,1:3] ALABAMA ARIZONA ARKANSAS 1970-01-01 15032.67 10148.42 7613.26 1971-01-01 15501.94 10560.54 7982.03 1972-01-01 15972.41 10977.53 8309.01 

Snooze forward by 1:

 > lag(x[1:3,1:3],1) ALABAMA ARIZONA ARKANSAS 1970-01-01 15501.94 10560.54 7982.03 1971-01-01 15972.41 10977.53 8309.01 

Put back on 1:

 > lag(x[1:3,1:3],k=-1) ALABAMA ARIZONA ARKANSAS 1971-01-01 15032.67 10148.42 7613.26 1972-01-01 15501.94 10560.54 7982.03 

As Dirk mentioned, be careful with the delay value in different time series packets. Note that xts treats this differently:

 > lag(as.xts(x[1:3,1:3]),k=1) ALABAMA ARIZONA ARKANSAS 1970-01-01 NA NA NA 1971-01-01 15032.67 10148.42 7613.26 1972-01-01 15501.94 10560.54 7982.03 
+4
source

For cross-section time series data, the plm package is very useful. It has a delay function that takes into account the nature of the data panel.

 library(plm) data("Produc", package="plm") dnow <- pdata.frame(Produc) head(lag(dnow$pcap,1)) ALABAMA-1970 ALABAMA-1971 ALABAMA-1972 ALABAMA-1973 ALABAMA-1974 NA 15032.67 15501.94 15972.41 16406.26 16762.67 

One problem with the package is that using with (either internally or conversion) gives the wrong answer.

 head(with(dnow, lag(pcap,1))) 15032.67 15501.94 15972.41 16406.26 16762.67 17316.26 

So be careful.

+4
source

All Articles