For and if , error when i need the next value

Hi guys, can you help me ?
I need make this
for(j in 1:i){
but the r tell:
Error in if (dataset$venda[j + 1] < dataset$venda[j]) { :
missing value where TRUE/FALSE needed

One of your greater than / less than statements is resolving as NA. I can't tell which one without looking at your dataframe, but you should run through the for loop and check that at each step there is actually a column to be compared.

1 Like

how about getting rid of the for loop entirely and using lag() or lead() from dplyr?

It should be a lot faster cut out some loop code so simplifies things.

But for the immediate problem, when comparing each entry with the next entry, have a think about what might be happening when you go to comparing the last entry with its next entry.


I agree with @thoughtfulnz that lag() or lead() would probably be great for this application if your for loop is actually this simple. However, if you need/want to stick with the for loop just changing your for(j in 1:i) call to for(j in 1:(i-1)) might solve your issue.

1 Like