string 将字符串转换为变量名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6034655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:06:25  来源:igfitidea点击:

Convert string to a variable name

stringr

提问by KnowledgeBone

I am using R to parse a list of strings in the form:

我正在使用 R 来解析以下形式的字符串列表:

original_string <- "variable_name=variable_value"

First, I extract the variable name and value from the original string and convert the value to numeric class.

首先,我从原始字符串中提取变量名称和值,并将值转换为数字类。

parameter_value <- as.numeric("variable_value")
parameter_name <- "variable_name"

Then, I would like to assign the value to a variable with the same name as the parameter_name string.

然后,我想将该值分配给与 parameter_name 字符串同名的变量。

variable_name <- parameter_value

What is/are the function(s) for doing this?

这样做的功能是什么?

回答by Greg

assign is what you are looking for.

分配是你正在寻找的。

assign("x", 5)

x
[1] 5

but buyer beware.

但买家要小心。

See R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f

参见 R 常见问题 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f

回答by Wojciech Sobala

You can use do.call:

您可以使用 do.call:

 do.call("<-",list(parameter_name, parameter_value))

回答by JohnBee

There is another simple solution found there: http://www.r-bloggers.com/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/

还有另一个简单的解决方案:http: //www.r-bloggers.com/converting-a-string-to-a-variable-name-on-the-fly-and-vice-versa-in-r/

To convert a string to a variable:

将字符串转换为变量:

x <- 42
eval(parse(text = "x"))
[1] 42

And the opposite:

而相反:

x <- 42
deparse(substitute(x))
[1] "x"

回答by saiteja

use x=as.name("string")you can use then use xto refer to the variable with name string.

usex=as.name("string")您可以使用 then usex来引用名称为字符串的变量。

I dunno if it answers your question correctly

我不知道它是否正确回答了你的问题

回答by Jozef Jano?ko

The function you are looking for is get():

您正在寻找的功能是get()

assign ("abc",5)
get("abc")

Confirming that the memory address is identical:

确认内存地址相同:

getabc <- get("abc")
pryr::address(abc) == pryr::address(getabc)
# [1] TRUE

Reference: R FAQ 7.21 How can I turn a string into a variable?

参考:R FAQ 7.21 如何将字符串转换为变量?

回答by Richie Cotton

strsplitto parse your input and, as Greg mentioned, assignto assign the variables.

strsplit解析你的输入,正如 Greg 提到的,assign分配变量。

original_string <- c("x=123", "y=456")
pairs <- strsplit(original_string, "=")
lapply(pairs, function(x) assign(x[1], as.numeric(x[2]), envir = globalenv()))
ls()

回答by CJB

assignis good, but I have not found a function for referring back to the variable you've created in an automated script. (as.nameseems to work the opposite way). More experienced coders will doubtless have a better solution, but this solution works and is slightly humorous perhaps, in that it gets R to write code for itself to execute.

assign很好,但我还没有找到一个函数来引用您在自动脚本中创建的变量。(as.name似乎以相反的方式工作)。更有经验的编码人员无疑会有更好的解决方案,但这个解决方案有效并且可能有点幽默,因为它让 R 为自己编写代码来执行。

Say I have just assigned value 5 to x(var.name <- "x"; assign(var.name, 5)) and I want to change the value to 6. If I am writing a script and don't know in advance what the variable name (var.name) will be (which seems to be the point of the assignfunction), I can't simply put x <- 6because var.namemight have been "y". So I do:

假设我刚刚将值 5 分配给x( var.name <- "x"; assign(var.name, 5)) 并且我想将值更改为 6。如果我正在编写脚本并且事先不知道变量名称 ( var.name) 将是什么(这似乎是assign函数),我不能简单地说,x <- 6因为var.name可能是"y". 所以我这样做:

var.name <- "x"
#some other code...
assign(var.name, 5)
#some more code...

#write a script file (1 line in this case) that works with whatever variable name
write(paste0(var.name, " <- 6"), "tmp.R")
#source that script file
source("tmp.R")
#remove the script file for tidiness
file.remove("tmp.R")

xwill be changed to 6, and if the variable name was anything other than "x", that variable will similarly have been changed to 6.

x将更改为 6,如果变量名称不是"x",则该变量也将类似地更改为 6。

回答by eigenfoo

I was working with this a few days ago, and noticed that sometimes you will need to use the get()function to print the results of your variable. ie :

几天前我正在处理这个问题,并注意到有时您需要使用该get()函数来打印变量的结果。IE :

varnames = c('jan', 'feb', 'march')
file_names = list_files('path to multiple csv files saved on drive')
assign(varnames[1], read.csv(file_names[1]) # This will assign the variable

From there, if you try to print the variable varnames[1], it returns 'jan'. To work around this, you need to do print(get(varnames[1]))

从那里,如果您尝试打印变量varnames[1],它会返回 'jan'。要解决此问题,您需要执行以下操作 print(get(varnames[1]))

回答by Vongo

Maybe I didn't understand your problem right, because of the simplicity of your example. To my understanding, you have a series of instructions stored in character vectors, and those instructions are very close to being properly formatted, except that you'd like to cast the right member to numeric.

也许我没有正确理解你的问题,因为你的例子很简单。据我了解,您在字符向量中存储了一系列指令,这些指令非常接近于正确格式化,只是您想将正确的成员转换为数字。

If my understanding is right, I would like to propose a slightly different approach, that does not rely on splitting your original string, but directly evaluates your instruction (with a little improvement).

如果我的理解是正确的,我想提出一种稍微不同的方法,它不依赖于拆分您的原始字符串,而是直接评估您的指令(略有改进)。

original_string <- "variable_name=\"10\"" # Your original instruction, but with an actual numeric on the right, stored as character.
library(magrittr) # Or library(tidyverse), but it seems a bit overkilled if the point is just to import pipe-stream operator
eval(parse(text=paste(eval(original_string), "%>% as.numeric")))
print(variable_name)
#[1] 10

Basically, what we are doing is that we 'improve' your instruction variable_name="10"so that it becomes variable_name="10" %>% as.numeric, which is an equivalent of variable_name=as.numeric("10")with magrittrpipe-stream syntax. Then we evaluate this expression within current environment.

基本上,我们正在做的是我们“改善”的指令variable_name="10",使之成为variable_name="10" %>% as.numeric,这是一个相当于variable_name=as.numeric("10")magrittr管流语法。然后我们在当前环境中评估这个表达式。

Hope that helps someone who'd wander around here 8 years later ;-)

希望能帮助那些 8 年后在这里闲逛的人;-)

回答by adam borkowski

If you want to convert string to variable inside body of function, but you want to have variable global:

如果要将字符串转换为函数体内的变量,但又希望变量为全局变量:

test <- function() {
do.call("<<-",list("vartest","xxx"))
}
test()
vartest

[1] "xxx"