[R] set argument of a function by string variable

Peter Langfelder peter.langfelder at gmail.com
Thu Feb 24 19:16:03 CET 2011


On Thu, Feb 24, 2011 at 10:03 AM, Duke <duke.lists at gmx.com> wrote:
> Hi folks,
>
> I am wondering if the following is possible: I want to control the arguments
> sent to a function by string variables. For example, instead of
>> heatmap.2( A, col=greenred(75) )
> I would want to have something like:
>> heatmap.2 ( paste(A, "col=greenred(75)", sep=",") )
>
> Is this possible to do that?

Of course (this is R, after all :)). Here's one solution:

fnc = "heatmap.2"
arguments = "A, col=greenred(75)"

eval(parse(text = paste(fnc, "(", arguments, ")")))

Example:

f = function(a, b) { a+b }
fnc= "f"
arguments = "a = 2,  b=3";
eval(parse(text = paste(fnc, "(", arguments, ")")))
[1] 5

Peter



More information about the R-help mailing list