11

I've noticed some strange behaviour in R reference classes when trying to implement some optimisation algorithm. There seems to be some behind-the-scenes parsing magic involved in initialising methods in a particular which makes it difficult to work with anonymous functions. Here's an example that illustrates the difficulty: I define a function to optimise (f_opt), a function that runs optim on it, and a reference class that has these two as methods. The odd behaviour will be clearer in the code

f_opt <- function(x) (t(x)%*%x)

do_optim_opt <- function(x) optim(x,f)
do_optim2_opt <- function(x)
  {
   f(x) #Pointless extra evaluation
   optim(x,f)
  }

optClass <- setRefClass("optClass",methods=list(do_optim=do_optim_opt,
                                 do_optim2=do_optim2_opt,
                                 f=f_opt))
oc <- optClass$new()
oc$do_optim(rep(0,2)) #Doesn't work: Error in function (par)  : object 'f' not found
oc$do_optim2(rep(0,2)) #Works. 
oc$do_optim(rep(0,2)) #Parsing magic has presumably happened, and now this works too. 

Is it just me, or does this look like a bug to other people too?

Triad sou.
  • 2,969
  • 3
  • 23
  • 27
sbarthelme
  • 111
  • 2

1 Answers1

6

This post in R-devel seems relevant, with workaround

do_optim_opt <- function(x, f) optim(x, .self$f)

Seems worth a post to R-devel.

Martin Morgan
  • 45,935
  • 7
  • 84
  • 112