Understanding Loop behaviour

Change the last if_else as follows:

if_else(I < max(I), 1L, I)

Change the 1 to 1L to force it to be integer. That should work.