-3

I need help figuring out how to improve a for loop. It doesn't necessarily needs to be apply, I just thought it was the best way after researching it on StackOverflow. I tried following the guides I found on StackOverflow, but I'm a newbie and believe I'm not getting a good grasp on the apply function.

This is a reconstruction of the snippet I'm trying to change:

for (j in 1:NROW(teste2) {
  for (z in 1:NROW(teste2)) {
        if(is.na(teste2$DATE[z]==Sys.Date()+j-1) | z==NROW(teste2)){
          teste2$SALDO[z] <- 0
        }else{
            if(teste2$SALDO[z]!=0 & teste2$DATE[z]==Sys.Date()+j-1){
              teste2$SALDO[z+1] <- teste2$PREVISAO_FINAL2[z] + teste2$SALDO[z+1]
          }else{
            teste2$SALDO[z] <- teste2$SALDO[z]
          }
        }
}

I tried doing the following:

for (j in 1:NROW(teste2) {
  rows = 1:NROW(teste2)
  saldo_fn <- function(z){
    return(if(is.na(teste2$DATE[z]==Sys.Date()+j-1) | z==NROW(teste2)){
      teste2$SALDO[z] <- 0
    }else{
      if(teste2$SALDO[z]!=0 & teste2$DATE[z]==Sys.Date()+j-1){
        teste2$SALDO[z+1] <- teste2$PREVISAO_FINAL2[z] + teste2$SALDO[z+1]
      }else{
        teste2$SALDO[z] <- teste2$SALDO[z]
      }
    })
}
teste2$SALDO <- sapply(rows, saldo_fn)
}

But when I run sum(teste2$SALDO) it gives a different value.

What am I doing wrong? how do I fix it?

Artem
  • 3,304
  • 3
  • 18
  • 41
automa7
  • 494
  • 4
  • 15
  • 3
    When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. This will make it easier to help you. – MrFlick Aug 09 '18 at 19:55

1 Answers1

0

You cannot use apply-family function to optimize the algorithm. The reason is the line:

teste2$SALDO[z+1] <- teste2$PREVISAO_FINAL2[z] + teste2$SALDO[z+1]

You are recursively changing the value of next element based on the value of current one.

It is possible avoid for-loop in by using recursion, i.e. if you see something like x[i+1] = x[i+1] + x[i] you should use either for-loops or recursive functions (I prefer for-loops they are much easier and there is no problem with call stack overflow), if you see something like z[i] = F(x[i], y[i]), where F is some function, you can use apply-family functions.

Artem
  • 3,304
  • 3
  • 18
  • 41