使用assign()循环R中的重命名变量 [英] Loop rename variables in R with assign()

查看:563
本文介绍了使用assign()循环R中的重命名变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在多个数据帧上重命名变量,但是分配不会起作用.这是我正在尝试的代码

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.

我正在使用一个循环来创建多个数据帧和每个变量中的不同变量,现在我需要重命名其中一些变量,以便以后可以将数据帧合并为一个.除重命名外,所有其他方法均有效.如果我使用colnames(DF)[[3]] <- "NewName"在常规调用中输入自己的数据帧名称和变量,但是以某种方式尝试使用Assign使其在循环中完成时,它却无能为力.

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.

推荐答案

在这里,您可以对环境中的所有data frames进行循环.由于您只在环境中查找data frame,因此可以避免接触任何其他变量的风险.关键是您应该assign对循环中的每个data frame进行新的更改.

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

这篇关于使用assign()循环R中的重命名变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆