I'm working out lineages for a drainage network and want to use a recursive function in R. There are 3k+ segments, so I will need to use memoization. But I am having trouble getting it to work. I can't get the function to assign to a list outside the function, which can then be referenced throughout iterating the function over all the segments. I'm not aware of any other specific memoization methods in R.
An example of the problem I'm having is below. In this version of a recursive Fibonacci function, I'd like to save the solutions to a list. But something is not working. The list is empty after using the function.
fib_list <- list()
fib <- function(n){
if(n <= 1){
return(n)
}
solution <- fib(n-1) + fib(n-2)
fib_list[[as.character(n)]] <- solution
return(solution)
}
fib(11)
-
Is there a reason you can't use a memoisation function from a package such as memoise.r-lib.org ?Spacedman– Spacedman2024年04月19日 12:36:02 +00:00Commented Apr 19, 2024 at 12:36
1 Answer 1
This is because the fib_list
inside the function only has scope within the function, and goes out of scope when the function returns.
One way to fix this is to use <<-
assignment, which looks at parent environments and finds the one you defined outside the function. Make this one change in the function:
fib_list[[as.character(n)]] <<- solution
Another way is to create a list in an environment and then assign to the list in that environment - environments let you do "pass by reference" in R rather than "pass by value".