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

查看:33
本文介绍了使用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 frame,因此您可以避免接触任何其他变量的风险.关键是你应该assign对循环中的每个数据框进行新的更改.

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天全站免登陆