Remko Duursma
Remko Duursma

Reputation: 2821

Evaluate function with parameters stored in an environment

Say I have this function

myfun <- function(a=1, b=2, c=3)a * b * c

I also have an environment where some of the arguments a,b,c are stored, but I don't know which ones (if any).

For example,

e <- new.env()
assign("a", 10, envir=e)

Now I can use do.call to use a from the e environment to evaluate myfun :

do.call(myfun, list(quote(a)), envir=e)

My question is, what if I don't know which possible arguments are actually stored in the e environment? I can get the listing as ls(envir=e) , but I have been unable to use this in a do.call statement.

For the moment, assume that e never contain objects that are not possible arguments to myfun (i.e. it can only contain a,b or c).

Upvotes: 1

Views: 82

Answers (1)

mnel
mnel

Reputation: 115392

You can coerce your environment to a list, and then use do.call

do.call(myfun, as.list(e))
# [1] 60

Upvotes: 3

Related Questions