0

I have several data frames. In each data frame there is a column called Current.Net.Price . I want to change the column names to different names. Therefore I have two lists:

Names <- c("name1","name2","name3","name4","name5")
dfList <- list(df1,df2,df3,df4,df5)

I tried something like this:

i=1
for (df in dfList) {
  names(df)[names(df) == "Current.Net.Price"] <- Names[i]
  i<-i+1
}

But when I call

View(dfList$df2)

the column is still named Current.Net.Price

Could someone help me please? :)

4
  • for clarification: each data.frame in dfList has got a column named "Current.Net.Price" and each of those column names is to be replaced with a different name obtained from Names, right? Commented Aug 14, 2015 at 10:15
  • Is it me, or does this sound like an XY problem? What are you ultimately trying to solve/achieve? Commented Aug 14, 2015 at 11:00
  • But if this is really what you want: df[,Names(i)] <- df$Current.Net.Price. Easier to check if you make a new column and no overwriting of original data. Commented Aug 14, 2015 at 11:03
  • Well, it is about some price lists of different months. In each is a price and I want to rename them because at the end I would like to merge all data frames. But your solution also works :) Commented Aug 14, 2015 at 11:15

2 Answers 2

3

Check this simple but similar example. It's all about how you access your dfList to exctract info about the data.frames's names.

 # 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]

}
Sign up to request clarification or add additional context in comments.

Comments

1

I believe when you loop like that (loop over items in a list/vector), the original objects don't get updated. E.g.,

l <- 1:5
for (i in l) {
  i <- 3
}
l
# [1] 1 2 3 4 5

The following works for me.

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.