R中的字符串到变量名 [英] String to variable name in R

查看:44
本文介绍了R中的字符串到变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在清理一个数据集,我需要根据另一个变量来选择变量.假设如果ID = 1,我需要在数据框中引入变量VAR01,如果ID = 2,我需要VAR02,等等.

I am cleaning a data set and I need to choose the variables depending on another variable. Let's say that if ID = 1, I need to introduce in the data frame the variable VAR01, if ID = 2, I need VAR02, and so on.

因此,我正在执行一个 for 循环,我使用 stringf 函数粘贴带有 ID 号的变量名称VAR".问题是我需要 R 才能将字符串理解为函数名.

Thus, I'm doing a for loop where I paste the variable name 'VAR' with the ID number with the stringf function. The problem is that I need R to understand the string as a function name.

我在论坛上找到了这个解决方案,但对我不起作用:

I've found in the forum this solution, which doesn't work for me:

> variable1 = c("monday", "tuesday", "wednesday")

> var_name = "variable1"

> eval(parse(text=var_name))
[1] "monday"    "tuesday"   "wednesday"

问题是我不能用它来引用变量:

The problem is I cannot use it to refer to the variable:

> eval(parse(text=var_name)) = c(1,2,3)
Error in file(filename, "r") : cannot open the connection
In addition: Warning message:
In file(filename, "r") :
cannot open file 'variable1': No such file or directory

有人解决了吗?

谢谢!

推荐答案

您可以使用 assign()

var_name <- 'test'
assign(var_name,1:3)
test

注意:assign 将在它被调用的环境中创建变量.因此,如果您要在这样的函数中调用 assign:

Note: assign as such will create the variable in the environment it is called. So, if you were to call assign within a function like this:

myfun <- function(var) { 
    assign(eval(substitute(var)), 5)
    print(get(var)) 
}

调用该函数会在函数内为 my_var 赋值 5,其环境仅在函数运行时创建并在此后销毁.

Calling the function assigns my_var a value of 5 within the function, whose environment is created only for the time the function is run and destroyed after.

> myfun("my_var")
# [1] 5

> my_var
# Error: object 'my_var' not found

因此,如果您想在函数调用后保留该值,则必须指定一个环境,您将在任务运行时拥有变量.例如,在全局环境:

So, if you want to retain the value after a function call, then, you'll have to specify an environment you'll have the variable thro' the time your task is run. For example, in the global environment:

myfun <- function(var, env = globalenv()) {
    assign(eval(substitute(var)), 5, envir = env)
    print(get(var))
}

> myfun("my_var")
# [1] 5
>  my_var
# [1] 5

这篇关于R中的字符串到变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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