0

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)
asked Apr 19, 2024 at 11:51
1
  • Is there a reason you can't use a memoisation function from a package such as memoise.r-lib.org ? Commented Apr 19, 2024 at 12:36

1 Answer 1

0

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".

answered Apr 19, 2024 at 12:40
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.