Search code examples
rfunctionlag

R function for creating, naming and lagging variables


I have some data like so:

a <- c(1, 2, 9, 18, 6, 45)
b <- c(12, 3, 34, 89, 108, 44)
c <- c(0.5, 3.3, 2.4, 5, 13,2)

df <- data.frame(a, b,c)

I need to create a function to lag a lot of variables at once for a very large time series analysis with dozens of variables. So i need to lag a lot of variables without typing it all out. In short, I would like to create variables a.lag1, b.lag1 and c.lag1 and be able to add them to the original df specified above. I figure the best way to do so is by creating a custom function, something along the lines of:

lag.fn <- function(x) {
    assign(paste(x, "lag1", sep = "."), lag(x, n = 1L)
    return (assign(paste(x, "lag1", sep = ".")
}

The desired output is:

a.lag1 <- c(NA, 1, 2, 9, 18, 6, 45)
b.lag1 <- c(NA, 12, 3, 34, 89, 108, 44)
c.lag1 <- c(NA, 0.5, 3.3, 2.4, 5, 13, 2)

However, I don't get what I am looking for. Should I change the environment to the global environment? I would like to be able to use cbind to add to orignal df. Thanks.


Solution

  • We can use mutate_all

    library(dplyr)
    df %>% 
       mutate_all(funs(lag = lag(.)))