Search code examples
rmatrixsapplycbind

Use Final Value In Iterative Process


Here is the code that I am working with:

## Round 1
b <- c(5000,2500)
r <- c(2,2.1) 
pm <- c(200,240)

I <- b*(r/1200) 
pi <- pm-I
end <- b-pi  
end

## Round 2 
b1 <- end 
r1 <- (2.3,2.3) 
I1 <- b1*(r/1200)
pi1 <- pm-I1 
end1 <- b1-pi1 
end1

This produces the proper output, which is shown below in the post. But, you can see how this might get annoying for about 30 rounds so I thought that I would be able to use a *sapply function. So I attempted to do:

r2<- matrix(c(2,2.1,2.3,2.3),nrow=2)
I2 <- sapply(b, function (x)
  x*(r2/1200)
)

pi2 <- sapply(I, function (l)
  pm-l )


end2 <- b-pi2
end2

Which gives:

[1,] 4808.333 4804.375
[2,] 2268.333 2264.375

This did not produce the desired output which is:

[1,] 4808.333 4616.347
[2,] 2264.375 2028.338

How exactly would I go about doing this because the "end" variables need the updated "b" value as shown in the starred part of the code below.

    **b1 <- end** 
    r1 <- 2.3 
    I1 <- b1*(r/1200)
    pi1 <- pm-I1 
    end1 <- b1-pi1 
    end1

Thank you for your time.

Edit

Pierre gives an answer below, but I have another question which is how would I do this process "n" number of times. Pierre's answer works for this specific question. But, I am trying to make this work when "r" and "r1" are joint in a matrix like

rate <- rbind(r,r1) 

And then use an sapply function kind of like:

t(sapply(b, function(x) {b <- b - (pm - b*(rate/1200));b}))

Any suggestions?


Solution

  • This is a situation where for loops shine:

    rlist <- list(r, r1)
    x <- vector("list", 2)
    for(i in 1:2) {b <- b - (pm - b*(rlist[[i]]/1200)); x[[i]] <- b}
    `names<-`(as.data.frame(x), c('x', 'y'))
    #         x        y
    #1 4808.333 4617.549
    #2 2264.375 2028.715