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.