[R] Substitution of the *value* of a variable

Thomas Lumley tlumley at u.washington.edu
Mon Jul 22 22:05:48 CEST 2002


On Mon, 22 Jul 2002, Daniel Mastropietro wrote:

> Hello,
>
> I have the following situation:
>
> Suppose I have the string "test(x)", and I want to substitute x by y. I
> know that this can be done by using the following commands:
>
> string <- parse( text="test(x)" )[[1]];
> do.call("substitute" , list(string, list(x=as.name("y")));
>
> Now, suppose that the variable name that plays the role of argument in
> "test(x)" may change. That is the string could be "test(z)", "test(w)",
> etc. I have the variable name stored in another variable, say 'varname'.
> That is, I have:
>
> varname <- "w";	# the value of varname is defined by the user and may change.
> string <- parse( text=paste("test(" , varname ,")") )[[1]];
>
> How can I have the *value* of 'varname' in 'string' be substituted by 'y'?

Define a variable for the second argument of substitute:
  replacement<-list(as.name("y"))
  names(replacement)<-varname
  do.call("substitute",list(string,replacement))

Incidentally, I wouldn't recommend the name `string' for something that
is actually an expression, especially in a help question...


	-thomas

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list