Werther
Werther

Reputation: 133

Is it possible to export an R function?

Suppose we have a function that, after a very long process, returns as output another function.

Just for illustration purposes, picture the following function:

f = function() {
  starting_time = Sys.time()
  a = 0
  while (difftime(Sys.time(), starting_time, units = "days") < 1) {
     a = a + 1
  }
  g = function(x) {
    a*x
  }
  return(g)
}

In our example, function f will run for a whole day and then it will return function g. We can assign function g to a variable by executing my_function = f().

The thing is that I would like f to run just once, so as to retrieve g, and then export g, so that I can share it without the need to run f again.

Preferrably, if possible, I would like a solution that doesn't involve saving the workspace. I wonder if, just as how write.csv allows us to export data frames without having to save the workspace, there is an analogous function to export functions.

Upvotes: 3

Views: 309

Answers (1)

dww
dww

Reputation: 31452

You can use saveRDS

f = function(x, ...) {
  mean(x, ...)
}

saveRDS(f, file='f.rds')
rm(f)

f = readRDS('f.rds')
f(1:3)
# [1] 2

If you want to save a text version of the function (so that the file is human-readable), you could use dput instead, although restoring the function from the file would then need eval(parse))

dput(f, file='f.txt')
g = eval(parse(text = readLines('f.txt')))
g(1:3)
# [1] 2

Upvotes: 11

Related Questions