When applying the stats::lag() function to a data frame, you probably expect it will pad the missing time periods with NA, but lag() doesn’t. For example:

> mydf <- data.frame(x=1:10, y=lag(1:10, 1))
> mydf
x y
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
7 7 7
8 8 8
9 9 9
10 10 10

Nothing happened. Here is an alternative lag function made for this situation. It pads the beginning of the output vecot with as many NA as there are lags, and then it truncates it to the same length as the input vector. These lengths assume your lags are calculated by variables within the same data frame.

lagpad <- function(x, k) {
if (!is.vector(x))
stop('x must be a vector')
if (!is.numeric(x))
stop('x must be numeric')
if (!is.numeric(k))
stop('k must be numeric')
if (1 != length(k))
stop('k must be a single number')
c(rep(NA, k), x)[1 : length(x)]
}

And the results work as expected:

> mydf <- data.frame(x=1:10, y=lag(1:10,1), z=lagpad(1:10, 1))
> mydf
x y z
1 1 1 NA
2 2 2 1
3 3 3 2
4 4 4 3
5 5 5 4
6 6 6 5
7 7 7 6
8 8 8 7
9 9 9 8
10 10 10 9

If you are using zoo or xts, see

Basic lag in R vector/dataframe.

### Like this:

Like Loading...

I was annoyed by the same thing. Here is a function I use to lag forward or backward.

vect_lag <- function(v, n=1, forward=FALSE) {

if (forward)

c(v[(n+1):length(v)], rep(NA, n))

else

c(rep(NA, n), v[1:(length(v) – n)])

}

If you cbind time series objects, then the NA padding is being done. Try cbind(ts(1:10),lag(ts(1:10),1))