Maxou
Maxou

Reputation: 25

How do I extract arguments in a function (written as a string) in R?

Let suppose I have defined a function by f <- function(x,y,z) {...}.

I would like to be able to transform an expression calling that function into a list of the parameters called by that function; it is the opposite of the do.call function.

For example, let us say I have such a function f, and I also have a string "f(2,1,3)". How can I transform the string "f(2,1,3)" into the list of the parameters list(x=1,y=2,z=3)?

Upvotes: 2

Views: 1086

Answers (2)

v44k3
v44k3

Reputation: 113

Alternatively:

f <- function(x,y,z) {...}
s <- "f(x = 2, y = 1, z = 3)"

c <- as.list(str2lang(s))
c[-1]
# $x
# [1] 2
# 
# $y
# [1] 1
# 
# $z
# [1] 3

I was looking for a solution to this a while ago in order to reconstruct a function call from a string. Hopefully this will be of use to someone who is looking for a solution to a similar problem.

Upvotes: 3

Josh O&#39;Brien
Josh O&#39;Brien

Reputation: 162471

After you've parsed your character string into an R expression, use match.call() to match supplied to formal arguments.

f <- function(x,y,z) {}
x <- "f(1,2,3)"

ee <- parse(text = x)[[1]]
cc <- match.call(match.fun(ee[[1]]), ee)
as.list(cc)[-1]
# $x
# [1] 1
# 
# $y
# [1] 2
# 
# $z
# [1] 3

Upvotes: 2

Related Questions