更改 R 中数据框列表中的列名 [英] 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
colnames of the ones in global environment
所以.
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 中的原始列名.为什么?lapply 是一个解决方案吗?谢谢
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
<小时>
编辑
如果要将data.frames赋值回全局环境,可以像这样修改代码:
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屋!