0

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

daaronr
  • 507
  • 1
  • 4
  • 12

1 Answers1

1

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)
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • Thank you. And @dash2 also pointed out that "Any time you feel tempted to mass assign variable names, use a list instead". – daaronr May 11 '21 at 13:31