Reputation: 273
I can compute a recursive variable with a for loop like this:
df <- as.data.frame(cbind(1:10))
df$it <- NA
for(i in 1:length(df$V1)) {
df$it <- 0.5*df$V1 + dplyr::lag(df$it, default = 0)
}
df
But how can I do this with a function on the fly? The following produces an error "C stack usage 15924032 is too close to the limit":
adstwm <- function(x){
0.5*x + adstwm(dplyr::lag(x, default = 0))
}
adstwm(df$V1)
I guess I need to define a stop for the process, but how?
Upvotes: 0
Views: 234
Reputation: 273
I can put the lagged for loop into the function without recursing the function:
df <- as.data.frame(cbind(1:10))
func.it2 <- function(x){
df$it2 <- NA
for(i in 1:length(df$V1)) {
df$it2 <- 0.5*df$V1 + 0.1*dplyr::lag(df$it2, default = 0)
}
df$it2
}
func.it2(df$V1)
df
df$it2 <- func.it2(df$V1)
df
That works. But why is df$it2 not available as a variable in df until I declare it (second last line) although it was already available in the for loop (line 5)?
Upvotes: 0
Reputation: 1724
You can use the cumulative sum to achieve the desired result. This sums all preceding values in a vector which is effectively the same as your recursive loop:
df$it_2 <- cumsum(0.5*df$V1)
If you do want to make recursive function, for example to address the comment below you can include an if statement that will make it stop:
function_it <- function(vector, length) {
if (length == 1) 0.5*vector[length]
else 0.5*vector[length] + 0.1*function_it(vector, length-1)
}
df$it <- NA
for(i in 1:length(df$V1)) {
df$it[i] <- function_it(df$V1,i)
}
df
However, you still need the for loop since the function is not vectorised so not sure if it really helps.
Upvotes: 1