1

I'd like to save computation time, by avoiding running the same function with the same arguments multiple times.

given the following code:

f1 <- function(a,b) return(a+b)
f2 <- function(c,d,f) return(c*d*f)

x <- 3
y <- 4

f2(1,2,f1(x,y))

let's assume that the computation of 'f' function argument is hard, and I'd like to cash the result somehow, so that I'd know if it had ever been executed before.

here is my main question:

I assume I can generate a key myself for f1(3,4), example: key <- paste('f1',x,y), do my own bookkeeping and avoid running it again.

however, is it possible for f2 to generate such a key from f automatically and return it to me? (for any function with any arguments)

if not / alternatively, before I pass f1(x,y) can I generate such a key in a generic manner, that would work for any function with any arguments?

thanks much

kamashay
  • 93
  • 1
  • 9

1 Answers1

0

Interesting question. I never thought about this.

A quick google search found this package: R.cache.

The function addMemoization takes a function as argument, and returns a function that should cache its results.

I haven't used this package myself, so I don't know how well it works, but it seems to fit what you are looking for.

JAD
  • 2,035
  • 4
  • 21
  • 35
  • great, I had no idea this is already implemented. followup your links I was able to find the following thread: https://stackoverflow.com/questions/7262485/options-for-caching-memoization-hashing-in-r . this led me to the package 'memoise' which also seems very relevant. – kamashay Jul 12 '17 at 08:16