1

I am trying to implement lazy evaluation in one of my package in R. I want to understand how it works. I have a situation where I don't want to evaluate all the output but instead, create a function to get those if necessary. For example, when I fit a linear model using lm function and I don't want to get the fitted values along with the lm object but rather evaluate them afterwards using another function. I have setup my situation as follows,

my_fun <- function(a, b, c){
  ret <- list(asq = a^2, bc = substitute(b * c))
  class(ret) <- "my_class"
  return(ret)
}

get_prod <- function(obj) {
  if(!class(obj) == "my_class") stop("unknow class")
  return(eval(obj$bc))
}

my_obj <- my_fun(1, 3, 4)
get_prod(my_obj)

I want to know, whether this is a good practice or not and will this make my evaluation faster in terms of memory and CPU consumption.

TheRimalaya
  • 4,232
  • 2
  • 31
  • 37
  • I'm not sure to what alternative you are comparing performance. You can always benchmark both alternatives. Anyway, I suggest to consider making use of closures since caching can improve performance. See this [answer](http://stackoverflow.com/a/33739307/1412059) for a simple example. – Roland Nov 23 '16 at 13:10

0 Answers0