Search code examples
rdataframelaglead

lag/lead entire dataframe in R


I am having a very hard time leading or lagging an entire dataframe. What I am able to do is shifting individual columns with the following attempts but not the whole thing:

require('DataCombine')
df_l <- slide(df, Var = var1, slideBy = -1)

using colnames(x_ret_mon) as Var does not work, I am told the variable names are not found in the dataframe.

This attempt shifts the columns right but not down:

 df_l<- dplyr::lag(df)

This only creates new variables for the lagged variables but then I do not know how to effectively delete the old non lagged values:

 df_l<-shift(df, n=1L, fill=NA, type=c("lead"), give.names=FALSE)

Solution

  • Use dplyr::mutate_all to apply lags or leads to all columns.

    df = data.frame(a = 1:10, b = 21:30)
    dplyr::mutate_all(df, lag)
        a  b
    1  NA NA
    2   1 21
    3   2 22
    4   3 23
    5   4 24
    6   5 25
    7   6 26
    8   7 27
    9   8 28
    10  9 29