Making the code more generic with `safe_ifelse`

The idea is to leverage `Rcpp`'s ifelse, but beware that it is currently broken (it does not handle NA correctly). 
I submitted a PR to Rcpp as well. https://github.com/RcppCore/Rcpp/pull/150