Hi, I have trouble figuring out how to use function factories inside an R6 class, see the reprex below.
library(R6)
# A function factory
fun_factory <- function(f) {
function(x) {
f(x)
}
}
double_x <- function(x) x * 2
# (1) when used outside of R6 class, the factory works as expected
fun <- fun_factory(double_x)
fun(42)
#> [1] 84
# (2) when he factory is used inside of class definition directly,
# R cannot find the 'double_x()' function
Foo <- R6::R6Class(
public = list(
fun = fun_factory(double_x)
)
)
foo <- Foo$new()
foo$fun(42)
#> Error in f(x): cannot find 'f' function
# (3) when assigned in the constructor, it does find the function
Foo <- R6::R6Class(
public = list(
initialize = function() {
self$fun <- fun_factory(double_x)
},
fun = NULL
)
)
foo <- Foo$new()
foo$fun(42)
#> [1] 84
Created on 2022-07-26 by the reprex package (v2.0.1)
For my use case, I would much prefer to assign fun
directly (2) instead of in the constructor (3).
I suspect the problem is with the difference in caller environments and the solution may be to use non-standard evaluation. However, those are two complicated topics that I haven't quite mastered yet.
Could someone please help me figure this out?