Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop rename variables in R with assign()

I am trying to rename a variable over several data frames, but assign wont work. Here is the code I am trying

assign(colnames(eval(as.name(DataFrameX)))[[3]], "<- NewName")
# The idea is, go through every dataset, and change the name of column 3 to
# "NewName" in all of them

This won't return any error (All other versions I could think of returned some kind of error), but it doesn't change the variable name either.

I am using a loop to create several data frames and different variables within each, now I need to rename some of those variables so that the data frames can be merged in one at a later stage. All that works, except for the renaming. If I input myself the names of the dataframe and variables in a regular call with colnames(DF)[[3]] <- "NewName", but somehow when I try to use assign so that it is done in a loop, it doesn't do anything.


2 Answers

Here is what you can do with a loop over all data frames in your environment. Since you are looking for just data frame in your environment, you are immune of the risk to touch any other variable. The point is that you should assign new changes to each data frame within the loop.

df1 <- data.frame(q=1,w=2,e=3)
df2 <- data.frame(q=1,w=2,e=3)
df3 <- data.frame(q=1,w=2,e=3)

# > df1
  # q w e
# 1 1 2 3
# > df2
  # q w e
# 1 1 2 3
# > df3
  # q w e
# 1 1 2 3

DFs=names(which(sapply(.GlobalEnv, is.data.frame)))
for (i in 1:length(DFs)){
    df=get(paste0(DFs[i]))
    colnames(df)[3]="newName"
    assign(DFs[i], df)
}

# > df1
  # q w newName
# 1 1 2       3
# > df2
  # q w newName
# 1 1 2       3
# > df3
  # q w newName
# 1 1 2       3
like image 52
989 Avatar answered Jan 27 '26 22:01

989


We could try ?eapply() to apply setnames() from the data.table package to all data.frame's in your global enviromnent.

library(data.table)
eapply(.GlobalEnv, function(x) if (is.data.frame(x)) setnames(x, 3, "NewName"))
like image 20
mtoto Avatar answered Jan 27 '26 23:01

mtoto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!