For loop doesn't work properly, returns NA for first IF