apostolos
apostolos

Reputation: 63

Implicit variable reference in R

How can I evaluate c[,2] through a call to z?

a <- c(1,2,3)
b <- c(4,5,6)
c <- cbind(a,b)
z <- "c[,2]"

eval(z) is not working.

Upvotes: 5

Views: 1216

Answers (2)

Tommy
Tommy

Reputation: 40861

If you really need to dynamically assemble a function call and then evaluate it, do.call is typically much better (and more efficient). It's a bit hard to pass the missing parameter though, but TRUE also works in this case:

z <- c[TRUE,2]

is equivalent to:

z <- do.call('[', list(c, TRUE, 2))

But here's a hack to get the missing symbol, which can then be used:

m <- quote(f(,))[[2]] # The elusive missing symbol
z <- do.call('[', alist(c, m, 2))

Upvotes: 3

Triad sou.
Triad sou.

Reputation: 2971

It may be below:

eval(parse(text=z))

Upvotes: 5

Related Questions