Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (50.2k points)

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?

1 Answer

0 votes
by (108k points)

With lapply function, you can change the Column Names of all the Data Frames in the Global Environment 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 the 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

For more information regarding the same, do refer the following link:

https://www.r-bloggers.com/renaming-data-frame-columns-in-lists-2/ 

If you want to get expert in R Programming visit this R Programming Course.

Browse Categories

...