Vense Rakić
Vense Rakić

Reputation: 1

Recursive function inside if else and for loop

I would like to write the recursive function in R that would do the following:

A_x(0) = 0
A_x(1) = q[4,1]+q[4,2] * A_x(0) = 1
A_x(2) = q[3,1]+q[3,2] * A_x(1) = 5
A_x(3) = q[2,1]+q[2,2] * A_x(2) = 23
A_x(4) = q[1,1]+q[1,2] * A_x(3) = 119

I wrote the following code:

n<-5
q<-matrix(c(4,5,3,4, 2, 3, 1,2,0,1), nrow=5, ncol=2, byrow=TRUE)
A_x <- function(x) {
  for(i in n:0) {
         if (x == 0)  return  (q[i,1])        
      else 
          return (q[i-1,1]+q[i-1,2]*A_x(x-1))     
 }
}    

Apparently it is not clear from my code that I would like to take one row higher each time when i do the for loop. Instead it looks like the function always takes values from cells q[4,1] and q[4,2].

Any help would be much appreciated, Vesna

Upvotes: 0

Views: 136

Answers (1)

Andrie
Andrie

Reputation: 179418

Try this:

A_x <- function(q, Ax, n){
  i <- nrow(q) - n
  if (i == 0)  q[i, 1]
  else 
    q[i, 1] + q[i, 2] * Ax[n]
}

Ax <- 0

for(i in 1:nrow(q)){
 Ax <- c(Ax, A_x(q, Ax, i))  
}
Ax

The result:

> Ax
[1]   0   1   5  23 119

Upvotes: 2

Related Questions