Loop rename variables in R with assign()

二次信任 提交于 2019-12-06 04:14:18

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

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