how to get value when a variable name is passed as a string

后端 未结 4 1322
别跟我提以往
别跟我提以往 2020-12-02 16:02

i write this code in R

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

which returns the value \"abc\"

Variable abc has a value

相关标签:
4条回答
  • 2020-12-02 16:32

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

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

    > abc <- 5
    > get("abc")
    [1] 5
    
    0 讨论(0)
  • 2020-12-02 16:32

    Here is an example to demonstrate eval() and get(eval())

    a <- 1
    b <- 2
    
    var_list <- c('a','b')
    
    for(var in var_list)
    {
      print(paste(eval(var),' : ', get(eval(var))))
    }
    

    This gives:

    [1] "a  :  1"
    [1] "b  :  2"
    
    0 讨论(0)
  • 2020-12-02 16:45

    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.

    0 讨论(0)
  • 2020-12-02 16:50

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

    assign(paste("a", "b", "c", sep = ""), 5)
    
    0 讨论(0)
提交回复
热议问题