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?
 
    