[英]Loop through list of data frames
我有幾個數據框。 在每個數據框中都有一個稱為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
有人可以幫我嗎? :)
檢查這個簡單但相似的示例。 這是關於如何訪問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]
}
我相信,當您像這樣循環(循環列表/向量中的項目)時,原始對象不會得到更新。 例如,
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"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.