Using the purrr
and dplyr
libraries:
library(purrr)
library(dplyr)
list2env(purrr::imap(list(dfa = dfa, dfb = dfb, dfc = dfc), ~ dplyr::rename(., Percentage = 1)), envir = .GlobalEnv)
Or using pipes you can write this as
list(dfa = dfa, dfb = dfb, dfc = dfc) %>%
purrr::imap(~ dplyr::rename(., Percentage = 1)) %>%
list2env(envir = .GlobalEnv)
How it works
If you put your dataframes into a list with the same names (ie dfa = dfa
) then purrr::imap
will apply a function over that list and preserve the names. The output of imap
will be a list where element names are still dfa, dfb, dfc
. This will be useful in step 3.
The function being mapped over the list is dplyr::rename
, which you can use positionally. Here Percentage = 1
is renaming the first column to be "Percentage".
Lastly, list2env
will unlist the dataframes into your global environment with the same names.
You could do something similar in base R
:
# names(x)[1] <- "Percentage" renames first column
list_of_dfs <- lapply(list(dfa, dfb, dfc), function(x) {
names(x)[1] <- "Percentage"
x})
names(list_of_dfs) <- c("dfa", "dfb", "dfc")
list2env(list_of_dfs, envir = .GlobalEnv)