Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

dataframe - Changing Column Names in a List of Data Frames in R

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...