LivingstoneM
LivingstoneM

Reputation: 1088

Loop over list of data frames and rename column names In R

I did like to loop over a list of dataframes that I have and rename the column names. Here is a sample of dataframes,

dput(df)
df1 <- structure(list(v1..x = c("Silva", "Brandon", "Mango"),
               t2.v = c("James","Jane", "Egg")),
          class = "data.frame", row.names = c(NA,  -3L))

dput(df2)
df2 <- structure(list(v1..x = c("Silva", "Brandon", "Mango"),
               t2.r = c("James","Jane", "Egg")),
          class = "data.frame", row.names = c(NA,  -3L))
dput(df3)
df3 <- structure(list(v1..x = c("Silva", "Brandon", "Mango"),
               t2.v = c("James","Jane", "Egg"),
               d3...c = c("James","Jane", "Egg")),
          class = "data.frame", row.names = c(NA,  -3L))

I would like to loop over the list of this dataframes and rename the columns. I have a list of columns I want to replace with, I did like to use setnames so that to skip absent columns incase it finds one in a dataframes.Here is what I tried but only changes first column

lst_df <- list(df1,df2,df3)
oldnames<- c('v1..x','t2.v','d3...c')
newnames <- c('v1','t2_v','d3')
lst <- lapply(lst_df, function(x) setNames(x, gsub(oldnames, newnames, names(x))) )

note columns in some dataframes might not be same length.Please help

Upvotes: 0

Views: 414

Answers (1)

Jon Nagra
Jon Nagra

Reputation: 1660

In this cases data.table may come in quite handy. Its setnames function is more flexible than setNames.

library(data.table)
oldnames<- c('v1..x','t2.v','d3...c')
newnames <- c('v1','t2_v','d3')

# convert df-s to data.table
lapply(lst_df, setDT)
# setnames function from data.table is quite flexible
lapply(lst_df, setnames, oldnames, newnames, skip_absent = TRUE)

Have into account that this will only change exact matches. If you want to change those string patterns, the easiest thing will likely be to run a for and use a regex.

Upvotes: 1

Related Questions