Rename dataframes in a list using a key

I have a list of dataframe and many of the columns will need to be renamed. It will be optimal to setup a key that I can use to rename the dataframe. The variables in the dataframe may or may not exist. I have been looking if there is a function that already do this but have not been able to find anything. The following example shows what I am trying to do.

# This is a dummy list with dataframes that may contain common variables
data_list <- list(
  dfx1 <- mtcars,
  dfx2 <- mtcars %>% rename(`mpg.1` = mpg, `cyl2` = cyl),
  dfx3 <- mtcars %>% rename(`mpg.11` = mpg),
  dfx4 <- mtcars %>% select(-mpg)
)

# Setup a key; the key does not have to be in this format
mykey <- list(
  mpg = c("mpg.1", "mpg.11"),
  cyl = c("cyl2")
)

# Is there a function that I can use to rename based in this key
lapply(x, fun, mykey)


Read more here: https://stackoverflow.com/questions/66321815/rename-dataframes-in-a-list-using-a-key

Content Attribution

This content was originally published by rjss at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: