I wonder how I can code recursion not using a for
loop
for a vector? Will it be more efficient?
My for
loop code:
fib <- function(n){
if (n==2){
return c(1,1)
}
if (n==1){
return c(1)
}
v=c(1,1)
for (i in 3:n ) {
v=c(v,v[i-1]+v[i-2])
}
return(v)
}
I look at a post and it says it is not efficient to append to a vector in R as the whole vector is re-created?