Search code examples
rdplyriterationpurrrr-glue

Assign a set of vectors based on on a character vector (automating code)


I want to do a series of assignments

rename2014 <- eas_dictionary$name2014
rename2015 <- eas_dictionary$name2015
rename2017 <- eas_dictionary$name2017

names(rename2014) <- eas_dictionary$true_name
names(rename2015) <- eas_dictionary$true_name
names(rename2017) <- eas_dictionary$true_name

eas_14 %<>% rename(all_of(rename2014))
eas_15 %<>% rename(all_of(rename2015))
eas_17 %<>% rename(all_of(rename2017))

(eas_dictionary is a tibble containing a data dictionary, but this doesn't matter.)

The point is that I want to automate the above code using on a vector years <- c("2014", "2015", "2017") so I don't have repeated code.

I try things like

for (i in seq_along(years)){
  rename[i] <- glue::glue('eas_dictionary$name', '{i}')
}

and

for (i in seq_along(years)){
  assign(glue('rename{i}') <- glue('eas_dictionary$name{i}'))
}

But these all throw errors. I'm just not getting a hang of the suntax


Solution

  • You can try using lapply :

    years <- c("2014", "2015", "2017")
    lapply(eas_dictionary[paste0('name', years)], function(x) 
           setNames(x, eas_dictionary$true_name)) -> result
    
    result
    

    It is not advised to create multiple individual objects in the environment but if for some reason you need to create them you can use list2env.

    list2env(result, .GlobalEnv)