swapped while loops for faster for loops, and '_' for is.na