0

I have three dataframes with one variable but it is labelled differently in each. Is there a way to rename the variable by position (or just by the dataframes each having a single variable) across all three dataframes rather than doing it individually.

e.g I would like to rename the column in dfa, dfb, dfc to "Percentage"

dfa <- data.frame(x = c(45, 55))

dfb <- data.frame(y = c(60, 40))

dfc <- data.frame(z = c(30, 70))

I tried using a loop like below - why doesn't this work?

for (i in c(dfa, dfb, dfc)) {
names(i)[1] <- "Percentage"
}
dspur2
  • 1
  • 2

1 Answers1

0

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

  1. 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.

  2. 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".

  3. 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)
LMc
  • 12,577
  • 3
  • 31
  • 43