Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Opposite of R's deparse(substitute(var))?

Tags:

r

reflection

I'm currently calling rp.slider from the tkrplot library with multiple arguments in a loop, for example:

rp.slider(rpplot, param1)
rp.slider(rpplot, param2)

etc.

Ideally, I'd like to do this within a loop, e.g.

for(i in 1:10) 
  rp.slider(rpplot, foo(paste(param,i,sep="")))

Where foo will encode the string to a variable name (symbol?). rp.slider converts the argument into a string using deparse(substitute(var)). Is there a foo function that will let me do this? I've tried as.symbol, as.name, and parse (among others) without success.

Any help would be much appreciated!


To clarify, deparse(substitute(x)) returns [1] "x" - I'd like a way of returning the same output from a string, i.e. which foo outputs [1] "x" for input deparse(substitute(foo("x")))? Is it possible?

like image 590
daveslanted Avatar asked Apr 04 '11 18:04

daveslanted


1 Answers

Tryeval(parse(text=...)) or eval(substitute(...)).

parse(text=...) turns the string in an expression, eval evaluates the expression. Be sure to use the text argument, as parse normally looks for a file. Forgetting that is a common mistake. See also ?parse and ?eval.

> a <- 10
> x <- deparse(substitute(a))
> eval(parse(text=x))
[1] 10

To show how to use it, your adjusted code :

for(i in 1:10)
  eval(parse(text=paste("rp.slider(rpplot,param",i,")",sep="")))

substitute substitutes values in a language object by the strings given in the second argument :

for(i in 1:10)
  eval(
    substitute(
      rp.slider(rpplot,x),
      list(x=as.name(paste("param",i,sep="")))
    )
  )

Or, using the example in the help files :

library(rpanel)
rpplot <- rp.control(title = "Demonstration of rp.tkrplot", h = 1,j=1)

redraw <- function(panel) {
  rp.tkrreplot(panel, tkrp)
}
x <- c('h','j')
rp.tkrplot(rpplot, tkrp, function(panel) plot((1:20)^panel$j, (1:20)^panel$h))

eval(parse(text=paste("rp.slider(rpplot, ",x[1]," , action = redraw,
    from = 0.05, to = 2.00, resolution = 0.05)")))

eval(
  substitute(
    rp.slider(rpplot, x, action=redraw, from=0.05, to=2.00, resolution=0.05),
    list(x = as.name(x[2]))
  )
)

The explanation why this is necessary, can be found within the source code of rp.slider. The construct to get the varname inside the function is not the standard used in R. In fact, the use of 'deparse(substitute())' is strongly discouraged, exactly for this reason. With most functions, as.expression("x") works to get the variable in using a variable name. Alas, the author of the rpanel package made this impossible.

like image 57
Joris Meys Avatar answered Nov 10 '22 15:11

Joris Meys