当变量名作为字符串传递时如何获取值

时间:2021-10-31 23:38:43

i write this code in R

我在R中写这段代码

paste("a","b","c") 

which returns the value "abc"

返回值“abc”

Variable abc has a value of 5(say) how do i get "abc" to give me the value 5 is there any function like as.value(paste("a","b","c")) which will give me the answer 5? I am making my doubt sound simple and this is exactly what i want. So please help me. Thanks in advance

变量abc的值为5(比如说)我如何得到“abc”给我值5是否有任何函数,如as.value(paste(“a”,“b”,“c”))这将给出我答案5?我让我怀疑听起来很简单,这正是我想要的。所以请帮助我。提前致谢

3 个解决方案

#1


29  

paste("a","b","c") gives "a b c" not "abc"

粘贴(“a”,“b”,“c”)给出“a b c”而不是“abc”

Anyway, I think you are looking for get():

无论如何,我认为你正在寻找get():

> abc <- 5
> get("abc")
[1] 5

#2


6  

An addition to Sacha's answer. If you want to assign a value to an object "abc" using paste():

萨莎的回答是一个补充。如果要使用paste()为对象“abc”赋值:

assign(paste("a", "b", "c", sep = ""), 5)

#3


6  

This is certainly one of the most-asked questions about the R language, along with its evil twin brother "How do I turn x='myfunc' into an executable function?" In summary, get, parse, eval , expression are all good things to learn about. The most useful (IMHO) and least-well-known is do.call , which takes care of a lot of the string-to-object conversion work for you.

这肯定是关于R语言最常见的问题之一,以及它邪恶的双胞胎兄弟“我如何将x ='myfunc'变成可执行函数?”总之,get,parse,eval,expression都是值得学习的好东西。最有用的(恕我直言)和最不为人所知的是do.call,它负责很多字符串到对象的转换工作。

#1


29  

paste("a","b","c") gives "a b c" not "abc"

粘贴(“a”,“b”,“c”)给出“a b c”而不是“abc”

Anyway, I think you are looking for get():

无论如何,我认为你正在寻找get():

> abc <- 5
> get("abc")
[1] 5

#2


6  

An addition to Sacha's answer. If you want to assign a value to an object "abc" using paste():

萨莎的回答是一个补充。如果要使用paste()为对象“abc”赋值:

assign(paste("a", "b", "c", sep = ""), 5)

#3


6  

This is certainly one of the most-asked questions about the R language, along with its evil twin brother "How do I turn x='myfunc' into an executable function?" In summary, get, parse, eval , expression are all good things to learn about. The most useful (IMHO) and least-well-known is do.call , which takes care of a lot of the string-to-object conversion work for you.

这肯定是关于R语言最常见的问题之一,以及它邪恶的双胞胎兄弟“我如何将x ='myfunc'变成可执行函数?”总之,get,parse,eval,expression都是值得学习的好东西。最有用的(恕我直言)和最不为人所知的是do.call,它负责很多字符串到对象的转换工作。