73

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?

Jaap
  • 81,064
  • 34
  • 182
  • 193
Zhang18
  • 4,800
  • 10
  • 50
  • 67

4 Answers4

103

You provided the answer in your question. Try get.

> get(x)
[1] 1 2 3
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
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]]
Greg Snow
  • 48,497
  • 6
  • 83
  • 110
11

What's wrong with either of the following?

eval(as.name(x))

eval(as.symbol(x))
Marek
  • 49,472
  • 15
  • 99
  • 121
RomanM
  • 111
  • 2
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.

Rui Vieira
  • 5,253
  • 5
  • 42
  • 55
mm441
  • 485
  • 5
  • 13