简体   繁体   中英

A loop in R to go through variable names and create new lagged variables

Hi I am trying to create new lagged variables that are based off existing variables in a loop. Here is my failed attempt:

varlist = c("retail", "grocery", "parks", "transit", "work", "residential")
for (x in varlist) {
  cases %<>% 
    mutate(x7 = lag(x,n=7L))
}

where the code would generate "retail7", "grocery7", etc. The issue seems to stem from when I say X7 i mean "retail7" or another variable 7, but it doesnt know what to make of it because its a string or something

Thanks

You don't need a loop to achieve this. Using some random example data this can be achieved via dplyr::mutate_at like so:

library(dplyr)

cases <- data.frame(state = rep(c("A", "B"), 10), retail = runif(20), grocery = runif(20), parks = runif(20), transit = runif(20), work = runif(20), residential = runif(20) )

cases <- cases %>%
  arrange(state) %>% 
  group_by(state) %>% 
  mutate_at(vars("retail", "grocery", "parks", "transit", "work", "residential"), list(`7` = ~ lag(.x, n = 7L)))
head(cases)   
#> # A tibble: 6 x 13
#> # Groups:   state [1]
#>   state retail grocery parks transit  work residential retail_7 grocery_7
#>   <chr>  <dbl>   <dbl> <dbl>   <dbl> <dbl>       <dbl>    <dbl>     <dbl>
#> 1 A     0.113   0.989  0.805   0.937 0.966       0.800       NA        NA
#> 2 A     0.981   0.755  0.274   0.491 0.191       0.897       NA        NA
#> 3 A     0.763   0.0676 0.780   0.249 0.363       0.592       NA        NA
#> 4 A     0.758   0.905  0.236   0.556 0.202       0.842       NA        NA
#> 5 A     0.0250  0.681  0.868   0.204 0.194       0.692       NA        NA
#> 6 A     0.592   0.404  0.509   0.478 0.692       0.128       NA        NA
#> # ... with 4 more variables: parks_7 <dbl>, transit_7 <dbl>, work_7 <dbl>,
#> #   residential_7 <dbl>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM