Loop rename variables in R with assign()

柔情痞子 提交于 2020-01-02 07:24:22

问题


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.


回答1:


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



回答2:


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"))


来源:https://stackoverflow.com/questions/37526921/loop-rename-variables-in-r-with-assign

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!