Search code examples
rcbind

R how to make assignments and reference a variable name converted from a string


My question is embedded in the code below.

I have created variable names from character strings, and I can assign values to those variable names (in this case, a list), but I can't do any simple operations on the lists unless I use the created variable names, which I do not want to do. How can I do simple operations with these lists, such as in the example, cbind?

id = c(96, 99)
namevector = paste("id.", per, sep = "")
assign(namevector[1],c(2,3))
assign(namevector[2],c(52,53))
cbind(id.96, id.99) # This is the desired answer. How do I get it, without using "id.96" or "id.99"?
#here are ideas that did not work 
cbind(namevector[1], namevector[2])
cbind(as.name(namevector[1]), as.name(namevector[2])) 



Solution

  • We can use mget to return the values of the objects in a list and then cbind the list elements to a single dataset with do.call

    do.call(cbind, mget(namevector))
    #      id.96 id.99
    #[1,]     2    52
    #[2,]     3    53
    

    assuming per is id