在R中的数据帧列表中更改列名 [英] Changing Column Names in a List of Data Frames in R

查看:176
本文介绍了在R中的数据帧列表中更改列名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:从以下列表中更改全局环境中所有数据框的列名称

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

全局数据框的名称环境

所以。

0)列名称为:

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

1)我有以下内容data.frames:df1,df2。

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

2)我将它们放在列表中:

2) I put them in a list:

  dfList <- list(df1,df2)

3)遍历列表:

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

但这会创建一个具有所需列名的新df,它不会更改df1,df2中的原始列名。为什么?请问是解决方案吗?谢谢

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

可以这样:

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

工作?

推荐答案

使用lapply,您可以执行以下操作。

With lapply you can do it as follows.

创建示例数据:

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") 

然后,使用 setNames 并将新列名的向量作为 setNames 的第二个参数提供:

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

如果您要分配数据。帧返回t在全局环境中,您可以像这样修改代码:

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)

这篇关于在R中的数据帧列表中更改列名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆