74

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?

1

4 Answers 4

105

You provided the answer in your question. Try get.

> get(x)
[1] 1 2 3
Sign up to request clarification or add additional context in comments.

Comments

19

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]]

Comments

10

What's wrong with either of the following?

eval(as.name(x))

eval(as.symbol(x))

1 Comment

What’s wrong with this solution is that it’s fantastically complex compared to get(x) if you know what happens under the hood. It’s basically an extremely complex wrapper around get(x).
3

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.

1 Comment

For this case you'll need get("a", x).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.