[R-pkg-devel] Trying to work around missing functionality

J C Nash profjcn@@h @ending from gm@il@com
Tue Aug 28 02:28:22 CEST 2018


In order to track progress of a variety of rootfinding or optimization
routines that don't report some information I want, I'm using the
following setup (this one for rootfinding).

TraceSetup <- function(ifn=0, igr=0, ftrace=FALSE, fn=NA, gr=NA){
# JN: Define globals here
   groot<-list(ifn=ifn, igr=igr, ftrace=ftrace, fn=fn, gr=gr, label="none")
   envroot <<- list2env(groot) # Note globals in FnTrace
   ## This generates a NOTE that
   ## TraceSetup: no visible binding for '<<-' assignment to ‘envroot’
##   envroot<-list2env(groot, parent=.GlobalEnv) # Note globals in FnTrace -- this does NOT work
   ## utils::globalVariables("envroot") # Try declaring here -- causes errors
# end globals
   envroot
}

FnTrace <- function(x,...) {
  # Substitute function to call when rootfinding
  # Evaluate fn(x, ...)
    val <- envroot$fn(x, ...)
    envroot$ifn <- envroot$ifn + 1 # probably more efficient ways
    if (envroot$ftrace) {
       cat("f(",x,")=",val," after ",envroot$ifn," ",envroot$label,"\n")
    }
    val
}


Perhaps there are better ways to do this, but this does seem to work quite well.
It lets me call a rootfinder with FnTrace and get information on evaluations of fn().
(There's another gr() routine, suppressed here.)

However, R CMD check gives a NOTE for

  TraceSetup: no visible binding for global variable ‘envroot’
  Undefined global functions or variables:
    envroot

The commented lines in TraceSetup suggest some of the things I've tried. Clearly I don't
fully comprehend how R is grinding up the code, but searches on the net seem to indicate
I am far from alone. Does anyone have any suggestion of a clean way to avoid the NOTE?

JN



More information about the R-package-devel mailing list