Method initialisation in R reference classes
Asked Answered
C

1

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?

Chafe answered 7/9, 2011 at 9:25 Comment(2)
Have you looked at help("force")?Abatement
I agree with Allan E. This sure looks like a classic example of lazy (non-)evaluation.Anthroposophy
S
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.

Sakai answered 7/9, 2011 at 13:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.