Ruser
Ruser

Reputation: 219

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

i write this code in R

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

which returns the value "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

Upvotes: 21

Views: 47035

Answers (5)

vinita vader
vinita vader

Reputation: 11

Here is a purrr example to do this for multiple vectors

text1 = "Somewhere over the rainbow"
text2 = "All I want for Christmas is you"
text3 = "All too well"
text4 = "Save your tears"
text5 = "Meet me at our spot"

songs = (map(paste0("text", 1:5), get) %>% unlist)
songs

This gives

[1] "Somewhere over the rainbow"     
[2] "All I want for Christmas is you"
[3] "All too well"                   
[4] "Save your tears"                
[5] "Meet me at our spot"

Upvotes: 0

pkumar90
pkumar90

Reputation: 71

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"

Upvotes: 2

Carl Witthoft
Carl Witthoft

Reputation: 21502

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.

Upvotes: 6

Mikko
Mikko

Reputation: 7755

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)

Upvotes: 7

Sacha Epskamp
Sacha Epskamp

Reputation: 47551

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

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

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

Upvotes: 36

Related Questions