How to optimize this nested for loop in R? : I need help figuring out how to improve a for loop. It doesn't necessarily needs to be an 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?