Basic lag in R vector/dataframe

Viewed 85126

Will most likely expose that I am new to R, but in SPSS, running lags is very easy. Obviously this is user error, but what I am missing?

x <- sample(c(1:9), 10, replace = T)
y <- lag(x, 1)
ds <- cbind(x, y)
ds

Results in:

      x y
 [1,] 4 4
 [2,] 6 6
 [3,] 3 3
 [4,] 4 4
 [5,] 3 3
 [6,] 5 5
 [7,] 8 8
 [8,] 9 9
 [9,] 3 3
[10,] 7 7

I figured I would see:

     x y
 [1,] 4 
 [2,] 6 4
 [3,] 3 6
 [4,] 4 3
 [5,] 3 4
 [6,] 5 3
 [7,] 8 5
 [8,] 9 8
 [9,] 3 9
[10,] 7 3

Any guidance will be much appreciated.

13 Answers

Using data.table:

> x <- sample(c(1:9), 10, replace = T)
> y <- data.table::shift(x)
> ds <- cbind(x, y)
> ds
      x  y
 [1,] 5 NA
 [2,] 4  5
 [3,] 3  4
 [4,] 3  3
 [5,] 4  3
 [6,] 8  4
 [7,] 1  8
 [8,] 7  1
 [9,] 9  7
[10,] 7  9

a simple way to do the same may be copying the data to a new data frame and changing the index number. Make sure the original table is indexed sequentially with no gaps

e.g.

tempData <- originalData
rownames(tempData) <- 2:(nrow(tempData)+1)

if you want it in the same data frame as the original use a cbind function

Two options, in base R and with data.table:

baseShiftBy1 <- function(x) c(NA, x[-length(x)])
baseShiftBy1(x)
[1] NA  3  8  4  8  9  1  5  9  5

data.table::shift(x)
[1] NA  3  8  4  8  9  1  5  9  5   

Data:

set.seed(123)
(x <- sample(c(1:9), 10, replace = T))
[1] 3 8 4 8 9 1 5 9 5 5

I went with a similar solution to Andrew's (dedicated function instead of xts or zoo), but with a terser formulation that I find easier to reason about:

lagpad <- function(x, k) {
  if (k == 0) { return(x) }
  k.pos <- max(0, k)
  k.neg <- max(0, -k)
  c(rep(NA, k.pos), head(x, -k.pos),  # empty if k<0, else lagging x
    tail(x, -k.neg), rep(NA, k.neg))  # empty if k>0, else leading x
}
Related