Why lag in r is not working for matrix? -


i trying lag matrix:

> b = matrix( c(2, 4, 3, 1, 5, 7),  nrow=3, ncol=2) > b      [,1] [,2] [1,]    2    1 [2,]    4    5 [3,]    3    7 > lag(b)      [,1] [,2] [1,]    2    1 [2,]    4    5 [3,]    3    7 

why lag(b) not give:

> lag(b)      [,1] [,2] [1,]    0    0 [2,]    2    1 [3,]    4    5 

it because lag shifts times of object, not data values. intended time series objects.

when lag used on plain matrix, b, lag.default method invoked. since there no time associated plain matrix assumes times 1, 2, ..., nrow(b) :

> time(b) [1] 1 2 3 attr(,"tsp") [1] 1 3 1 

and shifts times 1 start 0:

> time(lag(b)) [1] 0 1 2 attr(,"tsp") [1] 0 2 1 

use time series class if want combine objects have times. (the first column times in displays below.)

> library(zoo) > > # zooreg - regular series or > b.zr <- zooreg(b) > merge(b.zr, lag(b.zr))   b.zr.1 b.zr.2 lag(b.zr).1 lag(b.zr).2 0     na     na           2           1 1      2      1           4           5 2      4      5           3           7 3      3      7          na          na  > # zoo - irregular series > b.z <- zoo(b) > merge(b.z, lag(b.z))   b.z.1 b.z.2 lag(b.z).1 lag(b.z).2 1     2     1          4          5 2     4     5          3          7 3     3     7         na         na 

note difference between lag.zooreg can extend beyond range of original times producing 0 time , lag.zoo cannot because there no regularity assumption in latter.

we can use ts class assumes regularity 0 time can produced there no merge.ts making less useful here.


Comments

Popular posts from this blog

.htaccess - First slash is removed after domain when entering a webpage in the browser -

Automatically create pages in phpfox -

c# - Farseer ContactListener is not working -