Self-contained modified partial function

I would like to modify a random generation function (like rnorm) so that it can be used by another function. It needs to take the parameters as a vector, and also it needs to be a partial function (no other arguments except for the parameter vector).

Ideally it would not refer to anything outside its environment (so it can be used in parallel::parLapply without clusterExport).

So if we consider rnorm, this is where I am so far.

nx <- 20
x_func <- purrr::partial(rnorm, n = !!nx)
x_func2 <- function(theta){x_func(theta[1], theta[2])}

This won't work in parallel without clusterExport. Is there some way to do this? What would you do? Thank you!

you can be more explicit and dispense with a purrr::partial dependency

nx <- 5
x_func <- function(mean,sd) rnorm(nx,mean,sd)
x_func2 <- function(theta){x_func(theta[1], theta[2])}
1 Like

Thanks! Do you know the correct terminology for my question?

I suppose what we've done can be considered a function factory
10 Function factories | Advanced R (hadley.nz)

1 Like

@nirgrahamuk pointed me in the right direction on Function factories.

The base R force function can be used within a function definition in a similar way to !! is used within the arguments of purrr::partial (See question where I force evaluation of nx in x_func).


nx <- 20

fun <- function(nx){
  force(nx)
  function(theta){rnorm(nx, theta[1], theta[2])}
}

fun2 <- fun(nx)

The function fun2 is now self-contained with regards to nx and its argument is in the right format. You can test this out with the following code

library(parallel)
cl <- makeCluster(3)

theta <- replicate(10, c(0,1), simplify = FALSE)

parLapply(cl, X = theta, fun2)

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.