1

I have a bunch of data sets for which I would like to apply a renaming function to all of the columns. I have built the function and got to the point where I have a list of data frames with renamed columns but I am stuck on how to reassign these data frames back to the original ones. Could someone help me on this last step or advise on a simpler way of doing this?

A = data.frame(Var 1 = c(1,2,3,4), Var 2 = c(1,2,3,4))
B = data.frame(Var 3 = c(1,3,4,7), Var 4 = c(1,2,3,4))

better_names <- function(x) {
    names(x) <- names(x) %>% stringr::str_replace_all("\\s","_") %>% tolower
    return(x)
}

list_data <- list(A, B)
l <- lapply(list_data, better_names)
Addison
  • 143
  • 7
  • Did you want to keep the `data.frame`s in your `list_data` object? Try `setnames` from "data.table" to rename your `data.frame` columns in place. The body of `better_names` could be: `data.table::setnames(x, names(x) %>% stringr::str_replace_all("\\s","_") %>% tolower)[]` (but be aware that it's likely that `data.frame` "A" and `data.frame` "B" would also have the new names if you use this approach. – A5C1D2H2I1M1N2O1R2T1 Dec 04 '20 at 22:00

1 Answers1

1

We can name the output list and then use list2env to make changes in the objects that are present in the global env (not recommended though)

names(l) <- c('A', 'B')
list2env(l, .GlobalEnv)

-check the objects

A
#  var_1 var_2
#1     1     1
#2     2     2
#3     3     3
#4     4     4

B
#  var_3 var_4
#1     1     1
#2     3     2
#3     4     3
#4     7     4

data

A <- data.frame(`Var 1` = c(1,2,3,4), `Var 2` = c(1,2,3,4), check.names = FALSE)
B <- data.frame(`Var 3` = c(1,3,4,7), `Var 4` = c(1,2,3,4), check.names = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662