properly handle NA va NaN; inspired by data.table