字符串到R中的变量名

时间:2021-01-12 00:20:07

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.

我正在清理数据集,我需要根据另一个变量选择变量。假设如果ID = 1,我需要在数据帧中引入变量VAR01,如果ID = 2,我需要VAR02,依此类推。

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.

因此,我正在做一个for循环,我用变量名'VAR'和ID号与stringf函数粘贴。问题是我需要R将字符串理解为函数名。

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

Has anyone got a solution?

有没有人有解决方案?

Thanks!

谢谢!

3 个解决方案

#1


9  

You can use assign()

你可以使用assign()

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

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:

注意:assign as将在调用它的环境中创建变量。所以,如果你在这样的函数中调用assign:

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

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.

调用函数会在函数中为my_var赋值为5,其环境仅在函数运行和销毁之后创建。

> 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:

因此,如果您想在函数调用后保留该值,那么您必须指定一个环境,您将拥有变量thro'运行任务的时间。例如,在全球环境中:

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

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

#2


5  

You can use get:

你可以使用get:

result = get(var_name)

Although heavy use of get and set suggests you might want to start using list's of variables instead:

虽然大量使用get和set建议你可能想要开始使用list的变量:

l = list(variable1 = c(1,2,3))
l$variable1 = c(4,5,6) 

#3


2  

This is FAQ 7.21.

这是FAQ 7.21。

The most important part of that FAQ is the end where it tells you to use lists instead of doing this in the global environment. You mention that you want to do this in a data frame (which is already a list), so this becomes simpler. Try something like:

该FAQ最重要的部分是它告诉您使用列表而不是在全局环境中执行此操作的结束。您提到要在数据框(已经是列表)中执行此操作,因此这变得更简单。尝试以下方法:

mydf <- data.frame( g=c('a','b','c') )
ID <- 1

mydf[[ sprintf("VAR%02d",ID) ]] <- 1:3
mydf

Using eval(parse(text=...)) in this case is like saying that you know how to get from New York City to Boston and therefore ask for directions from your origin to New York and directions from Boston to your destination. In some cases this might not be too bad, but it is a bit out of the way if you are trying to get from London to Paris (and your example has you going from New York to Boston via Mars). See fortune(106).

在这种情况下使用eval(parse(text = ...))就像是说你知道如何从纽约市到达波士顿,因此要求从你的出发地到纽约的路线以及从波士顿到目的地的路线。在某些情况下,这可能不会太糟糕,但是如果你想要从伦敦到达巴黎(例如,你通过火星从纽约到波士顿)的例子有点偏僻。见财富(106)。

#1


9  

You can use assign()

你可以使用assign()

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

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:

注意:assign as将在调用它的环境中创建变量。所以,如果你在这样的函数中调用assign:

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

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.

调用函数会在函数中为my_var赋值为5,其环境仅在函数运行和销毁之后创建。

> 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:

因此,如果您想在函数调用后保留该值,那么您必须指定一个环境,您将拥有变量thro'运行任务的时间。例如,在全球环境中:

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

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

#2


5  

You can use get:

你可以使用get:

result = get(var_name)

Although heavy use of get and set suggests you might want to start using list's of variables instead:

虽然大量使用get和set建议你可能想要开始使用list的变量:

l = list(variable1 = c(1,2,3))
l$variable1 = c(4,5,6) 

#3


2  

This is FAQ 7.21.

这是FAQ 7.21。

The most important part of that FAQ is the end where it tells you to use lists instead of doing this in the global environment. You mention that you want to do this in a data frame (which is already a list), so this becomes simpler. Try something like:

该FAQ最重要的部分是它告诉您使用列表而不是在全局环境中执行此操作的结束。您提到要在数据框(已经是列表)中执行此操作,因此这变得更简单。尝试以下方法:

mydf <- data.frame( g=c('a','b','c') )
ID <- 1

mydf[[ sprintf("VAR%02d",ID) ]] <- 1:3
mydf

Using eval(parse(text=...)) in this case is like saying that you know how to get from New York City to Boston and therefore ask for directions from your origin to New York and directions from Boston to your destination. In some cases this might not be too bad, but it is a bit out of the way if you are trying to get from London to Paris (and your example has you going from New York to Boston via Mars). See fortune(106).

在这种情况下使用eval(parse(text = ...))就像是说你知道如何从纽约市到达波士顿,因此要求从你的出发地到纽约的路线以及从波士顿到目的地的路线。在某些情况下,这可能不会太糟糕,但是如果你想要从伦敦到达巴黎(例如,你通过火星从纽约到波士顿)的例子有点偏僻。见财富(106)。