我有几个数据框。在每个数据框中都有一个名为Current.Net.Price的列。我想将列名更改为不同的名称。 因此我有两个清单:
Names <- c("name1","name2","name3","name4","name5")
dfList <- list(df1,df2,df3,df4,df5)
我试过这样的事情:
i=1
for (df in dfList) {
names(df)[names(df) == "Current.Net.Price"] <- Names[i]
i<-i+1
}
但是当我打电话时
View(dfList$df2)
该列仍然名为Current.Net.Price
有人可以帮帮我吗? :)答案 0 :(得分:1)
检查这个简单但类似的例子。 这是关于如何访问dfList以提取有关data.frames名称的信息的全部内容。
# data frames
dt1 = data.frame(x = 1:3,
y = 5:7)
dt2 = data.frame(x = 1:4,
z = 5:8)
dt3 = data.frame(y = 1:10,
x = 21:30)
Names = c("A","B","C")
dfList <- list(dt1,dt2,dt3)
for (i in 1:length(dfList)) {
names(dfList[[i]])[names(dfList[[i]])=="x"] = Names[i]
}
答案 1 :(得分:1)
我相信当你像那样循环(循环遍历列表/向量中的项目)时,原始对象不会更新。如,
l <- 1:5
for (i in l) {
i <- 3
}
l
# [1] 1 2 3 4 5
以下适用于我。
df1 <- data.frame("x" = rnorm(5),"Current.Net.Price"=1:5)
df2 <- data.frame("x" = rnorm(5),"Current.Net.Price"=1:5)
df3 <- data.frame("x" = rnorm(5),"Current.Net.Price"=1:5)
df4 <- data.frame("x" = rnorm(5),"Current.Net.Price"=1:5)
df5 <- data.frame("x" = rnorm(5),"Current.Net.Price"=1:5)
Names <- c("name1","name2","name3","name4","name5")
dfList <- list(df1=df1,df2=df2,df3=df3,df4=df4,df5=df5)
for (i in 1:5) {
names(dfList[[i]])[names(dfList[[i]]) == "Current.Net.Price"] <- Names[i]
}
sapply(dfList, colnames)
# df1 df2 df3 df4 df5
# [1,] "x" "x" "x" "x" "x"
# [2,] "name1" "name2" "name3" "name4" "name5"