Execute the function as a parameter before evaluating it in R?

Is there any way, given by the function passed as a parameter, to change its string of input parameters before evaluating it?

Here's the pseudo code for what I hope to achieve:

test.func <- function(a, b) { # here I want to alter the b expression before evaluating it: b(..., val1=a) } 

Given the function call passed to b , I want to add to a as another parameter, without always requiring to specify ... in the call to b . So the output from this call to test.func should be:

 test.func(a="a", b=paste(1, 2)) "1" "2" "a" 

Edit:

Another way that I could see doing something similar would be if I could assign an additional parameter in the scope of the parent function (again, like pseudocode); in this case, a will be within t1 and, therefore, t2, but not globally assigned:

 t2 <- function(...) { paste(a=a, ...) } t1 <- function(a, b) { local( { a <<- a; b } ) } t1(a="a", b=t2(1, 2)) 

This is somewhat similar to currying in that I insert a parameter inside the function itself.

Edit 2:

Just add one more comment to this: I understand that one of the related approaches may be to use prototype programming, "so things will be inherited (which can be achieved using a proto package ). But I was hoping for an easy way to just change the input parameters before grade in R.

+4
source share
2 answers

Are you checking substitute ? I don't know if this suits you, but you can use the fact that it returns a hidden list structure that you can change below

 test.func <- function(a, b) { f <- substitute(b) f[["val1"]] <- a eval(f) } test.func(a="a", b=paste(1, 2)) # "1 2 a" 
+2
source

What do you want to do for expression B? Do you want to dynamically add behavior? Then there is a decorator pattern in your problem. Want to add more behavior? Proxy. Do I need to change any behavior for another under certain circumstances? Strategy.

You are much better off relying on design patterns that work and make you more efficient, regardless of the language you use, than you are trying to use specific language specifics that allow you to change the behavior of the strategy.

0
source

Source: https://habr.com/ru/post/1306169/


All Articles