R – Changing Column Names in a List of Data Frames in R

dataframer

Objective: Change the Column Names of all the Data Frames in the Global Environment from the following list

colnames of the ones in global environment

So.

0) The Column names are:

 colnames = c("USAF","WBAN","YR--MODAHRMN") 

1) I have the following data.frames: df1, df2.

2) I put them in a list:

  dfList <- list(df1,df2)

3) Loop through the list:

 for (df in dfList){
   colnames(df)=colnames
 }

But this creates a new df with the column names that I need, it doesn't change the original column names in df1, df2. Why? Could lapply be a solution? Thanks

Can something like:

 lapply(dfList, function(x) {colnames(dfList)=colnames})

work?

Best Answer

With lapply you can do it as follows.

Create sample data:

df1 <- data.frame(A = 1, B = 2, C = 3)
df2 <- data.frame(X = 1, Y = 2, Z = 3)
dfList <- list(df1,df2)
colnames <- c("USAF","WBAN","YR--MODAHRMN") 

Then, lapply over the list using setNames and supply the vector of new column names as second argument to setNames:

lapply(dfList, setNames, colnames)
#[[1]]
#  USAF WBAN YR--MODAHRMN
#1    1    2            3
#
#[[2]]
#  USAF WBAN YR--MODAHRMN
#1    1    2            3

Edit

If you want to assign the data.frames back to the global environment, you can modify the code like this:

dfList <- list(df1 = df1, df2 = df2)
list2env(lapply(dfList, setNames, colnames), .GlobalEnv)