Automatically generate new variable names using dplyr mutate

后端 未结 3 1676
谎友^
谎友^ 2020-12-11 08:09

I would like to create variable names dynamically while using dplyr; although, I’d be fine with a non-dplyr solution as well.

For Example:

data(iris)         


        
3条回答
  •  暖寄归人
    2020-12-11 08:49

    Since you're also happy with a non-dplyr, try this:

    lagger <- function(x, n) c(rep(NA,n), head(x,-n) )
    iris[paste0("lag_", names(iris) )] <- lapply(iris, lagger, n=1)
    
    head(iris,2)[-(1:5)]
    #  lag_Sepal.Length lag_Sepal.Width lag_Petal.Length lag_Petal.Width lag_Species
    #1               NA              NA               NA              NA          NA
    #2              5.1             3.5              1.4             0.2           1
    

提交回复
热议问题