Opposite R deparse (replace (var))?

I am currently rp.slider from the tkrplot library with several arguments in a loop, for example:

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

and etc.

Ideally, I would like to do this in a loop, for example.

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

Where foo will encode the string for the variable name (character?). rp.slider converts an argument to a string using deparse(substitute(var)) . Is there a foo function that will allow me to do this? I tried as.symbol , as.name and parse (among other things) with no success.

Any help would be greatly appreciated!


To clarify, deparse(substitute(x)) returns [1] "x" - I would like to return the same output from the string, i.e. which foo prints [1] "x" for input deparse(substitute(foo("x"))) ? Is it possible?

+4
source share
2 answers

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

parse(text=...) turns the string into an expression, eval evaluates the expression. Be sure to use the text argument, as parse usually looks for a file. Forgetting it 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, customized code:

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

substitute replaces the values ​​in the language object with the lines specified 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])) ) ) 

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

+12
source

The rp.slider function looks like it is in rpanel, not tkrplot.

A possible alternative is to use the tkexamp function in the TeachingDemos package, it builds tk gui for the chart (using tkrplot) based on the list, you can build the list in your loop, and then call tkexamp. Or you can look at the tkexamp code to see how it analyzes the list (in a loop) to create tk controls, although looking at the code may scare you away from this idea.

0
source

Source: https://habr.com/ru/post/1346607/


All Articles