I have an R function to calculate the logistic map, as below, using a for loop. But is there a way to change it (e.g. vectorise it) so that it doesn't use a loop?
logistic_map <- function(x, # starting condition
r, # rate parameter
N) { # number of iterations
results <- numeric(length = N + 1)
results[1] <- x
for (i in seq_len(N)) {
results[i + 1] <- r * results[i] * (1 - results[i])
}
data.frame(i = c(0, seq_len(N)),
x = results)
}
I've looked at the apply()
family of functions and those in purrr
, but I'm struggling to determine whether this is even possible. I'm tempted to conclude that it's not possible, just because each step relies entirely on the previous one, but it's entirely possible there's an elegant solution to this that I haven't been able to find.
Can I do this without a for loop?