r-lib / R6

Encapsulated object-oriented programming for R
https://R6.r-lib.org
Other
407 stars 56 forks source link

do.call for class methods #83

Closed terrytangyuan closed 8 years ago

terrytangyuan commented 8 years ago

For example, I have a Class1$addKV("key1", "value1") function. Is there a way to use do.call() to call it since I want to make this more general.

Thanks!

wch commented 8 years ago

You can use do.call(Class1$addKV, list("key1", "value1")).

terrytangyuan commented 8 years ago

Sure, but I meant something like this do.call("AnyClassName$addKV", list("key1", "value1")).

wch commented 8 years ago

It depends on which part you want to be a string. If it's the object:

objName <- "AnyClassName"

obj <- get(objName)
do.call(obj$addKV, list("key", "value"))

If it's the method:

methodName <- "addKV"

do.call(obj[[methodName]], list("key", "value"))

If you want to use a single string for both, you could use eval, although it's a little gross:

f <- eval("AnyClassName$addKV")
do.call(f, list("key", "value"))
terrytangyuan commented 8 years ago

Got it! This is very helpful! Thanks!

wch commented 8 years ago

Oops, the eval code should be:

f <- eval(parse(text = "AnyClassName$addKV"))
terrytangyuan commented 8 years ago

Yep got the idea! Thanks!