Skip to content

Modify Apply() to prevent errors with 'builtin' type functions in R>=4.6

FYI @abatalla

As stated in the R-devel NEWS.md and explained in https://earth.bsc.es/gitlab/es/csindicators/-/issues/54#note_354503, the development version of R has introduced a bugfix in the environment() function that makes it return an error when applied to functions of type 'builtin', which don't have an associated environment. This affects the following line in Apply(): https://earth.bsc.es/gitlab/ces/multiApply/-/blob/master/R/Apply.R#L616

  Error in environment(fun) <- fun_env : 
    cannot set attribute on a 'builtin'

This will cause problems in the future when using Apply() with any function of type 'builtin', as in one of the examples in the README:

library(multiApply)

A <- array(1:20, c(5, 2, 2))
B <- array(1:20, c(5, 2, 2))

D <- Apply(data = list(A, B), 
           target_dims = c(2, 3), 
           fun = "%*%")$output1

Previously, environment(fun) made no changes to fun if it was of type 'builtin'. Based on that, the easiest solution might be to add an if condition such as:

if (typeof(fun) == "closure") {
  environment(fun) <- fun_env
}

However, I'm not actually sure what the exact repercussions would be. We need to think about the best solution and test a variety of scenarios, if possible under R-devel.

Cheers,

Victòria

Edited by vagudets