How to optimize this nested for loop in R?

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



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)) 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) 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?





When asking for help, you should include a simple 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 9 at 19:55




1 Answer
1



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


apply


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.


for


x[i+1] = x[i+1] + x[i]


for


for


z[i] = F(x[i], y[i])


apply






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

make 2 or more post in bootsrap

Store custom data using WC_Cart add_to_cart() method in Woocommerce 3

Firebase Auth - with Email and Password - Check user already registered