Access variable value where the name of variable is stored in a string

RVariablesR Faq

R Problem Overview


Similar questions have been raised for other languages: C, sql, java, etc.

But I'm trying to do this in R.

I have:

ret_series <- c(1, 2, 3)
x <- "ret_series"

How do I get (1, 2, 3) by calling some function / manipulation on x, without direct mentioning of ret_series?

R Solutions


Solution 1 - R

You provided the answer in your question. Try get.

> get(x)
[1] 1 2 3

Solution 2 - R

For a one off use, the get function works (as has been mentioned), but it does not scale well to larger projects. it is better to store you data in lists or environments, then use [[ to access the individual elements:

mydata <- list( ret_series=c(1,2,3) )
x <- 'ret_series'

mydata[[x]]

Solution 3 - R

What's wrong with either of the following?

eval(as.name(x))

eval(as.symbol(x))

Solution 4 - R

Note that some of the examples above wouldn't work for a data.frame.

For instance, given

x <- data.frame(a=seq(1,5))

get("x$a") would not give you x$a.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZhang18View Question on Stackoverflow
Solution 1 - RJoshua UlrichView Answer on Stackoverflow
Solution 2 - RGreg SnowView Answer on Stackoverflow
Solution 3 - RRomanMView Answer on Stackoverflow
Solution 4 - Rmm441View Answer on Stackoverflow