I'm writing a function, which results I want to write into a list. However, each function call requires to use the results from the previous function call.
So I'm unsure about how to best make sure that each function call (I'm using an lapply approach) uses the updated results. i've read about <<- and assign, but still don't really now what the cleanest/correctest way would be.
Example:
My naive/wrong approach is:
results <- list()
my_function <- function(x)
{
result <- ifelse(length(results) == 0, 0, results[length(results)])
2 * x + unlist(result)
}
results <- lapply(1:5, my_function)
which returns:
[[1]]
[1] 2
[[2]]
[1] 4
[[3]]
[1] 6
[[4]]
[1] 8
[[5]]
[1] 10
What I would like to return is:
[[1]]
[1] 2
[[2]]
[1] 6
[[3]]
[1] 12
[[4]]
[1] 20
[[5]]
[1] 30
So how do I feed the previous results into the function call?
NOTE: the example function is really a very simple example. I know I could probably do a simple cumsum here. But my real life function is way more complicated and not a simple computation of a number.