R - 在每个数据帧中使用filename重命名特定列

时间:2018-05-15 11:54:30

标签: r dataframe

我想用文件名批量替换第5列名称,如下所示:

for (i in dflist){
names(i)[5]<-i
}

问题必须在我的列表中,因为如果我尝试here中的任何方法,我会得到NULL s。各种其他方法抱怨向量或维度。如何获取我可以循环的数据框列表或lapply

1 个答案:

答案 0 :(得分:0)

df1 <- data.frame(colA=rnorm(5), colB=rnorm(5), colC=rnorm(5))
df2 <- data.frame(colA=rnorm(5), colB=rnorm(5), colC=rnorm(5))
df3 <- data.frame(colA=rnorm(5), colB=rnorm(5), colC=rnorm(5))

# Create a list with dataframes
dflist <- list(df1=df1,df2=df2,df3=df3)

#If you need to do this for many dataframes and you do not want to manually create names
# you can all dataframes into the list based on the pattern of their names (or you can add all dataframes)
dflist <- mget(ls(pattern = "^df\\d+$"))

for( i in 1:length(dflist)) names( dflist[[i]])[2] <- names(dflist)[i]

dflist
# $df1
# colA        df1       colC
# 1 -0.1422569 -0.9708563 -0.7436538
# 2 -1.4446162  0.5055604 -0.4629691
# 3 -0.3074055  1.0433459  0.1666820
# 4  0.5022005  0.1734464  0.5055267
# 5  1.0109980 -1.6338863  0.8307362
# 
# $df2
# colA        df2        colC
# ...

您可以从列表中提取这些新数据框并将它们放回您的环境中:

list2env(dflist, .GlobalEnv)
head(df1)
#         colA         df1       colC
#1  1.09331854 -0.25656013 -0.3371509
#2 -0.10231413 -1.57529234  0.1046795
#3 -2.18463139  1.12416514 -0.3130566
#4  0.66743048 -0.84002134  0.8222045
#5 -0.02061098 -0.09697982 -1.7822345