Search code examples
rlag

lag of multiple column using r


I have a data frame like this

    MSFT     AAPL     GOOGL
1 21.11067 4.975767  94.04000
2 20.91273 5.663524  97.50684
3 20.05333 5.681336  90.57909

want to create a file with one lag of the previous data like

   MSFT     AAPL     GOOGL
1 20.91273 5.663524  97.50684
2 20.05333 5.681336  90.57909
3 20.09447 5.239416  99.60738

Trying this code to solve it

Lagcolmean <- lapply(names(colmean), function(x){lag(colmean[[x]],k=1)
})

But it is not working. Could you help me in this regard?


Solution

  • 1) indexing lag is normally used with time series such as "ts", "zoo" and "xts" objects. For a data frame, just remove the first row:

    DF[-1, ]
    

    2) rollapplyr If you want to use rollapply as in the code in the question then try this:

    rollapplyr(DF, 2, function(x) x[2])
    

    or equivalently:

    rollapplyr(DF, 2, "[", 2)
    

    3) dplyr Alternately, the dplyr package does define a lead and lag which work with data frames:

    library(dplyr)
    DF %>% mutate_all(lead)