Hello,
I am trying to build a function f
that wraps any other function g
and returns two things:
- the result of
g
applied to the supplied arguments - the call of
g
I came up with the following:
my_function <- function(.f){
function(...){
the_functions <- enquo0(.f)
the_args <- enquos0(...)
list(the_result = .f(...),
the_function = the_function,
the_args = the_args)
}
}
which kinda works, but something surprising (to me) happens:
sqrt2 <- my_function(sqrt)
If I call it once on sqrt2
I get something looking ok:
sqrt2(2)
$the_result
[1] 1.414214
$the_function
<quosure>
expr: ^sqrt
env: global
$the_args
$the_args[[1]]
<quosure>
expr: ^2
env: empty
but if I run it a second time, the result of the_function
is now different:
$the_result
[1] 1.414214
$the_function
<quosure>
expr: ^.Primitive("sqrt")
env: empty
$the_args
$the_args[[1]]
<quosure>
expr: ^2
env: empty
the quosure the_function
now shows ^.Primitive("sqrt")
instead of just sqrt
as before. The environment is also different, and I don’t understand why that is.
Also, ideally, what I’d like would to get an output similar to this:
$the_result
[1] 1.414214
$the_call
sqrt(2)
basically sqrt2
would return the result of sqrt
applied to 2, and the call, in this case, sqrt(2)
(notice I’m talking about sqrt()
not sqrt2()
.
Something like this would be nice as well:
mtcars %>%
filter2(am == 1)
here the returned call would look like filter(mtcars, am == 1)
. I fell like I’m getting close! Any help appreciated.