Search code examples
rnarcpparmadillo

RcppArmadillo: How to replace NAs in a vector with another vector


Setup

Let's say I have an x vector containing some NAs and a y vector containing the replacement for those NAs:

x <- c(NA, 2, NA, 4)
y <- c(80, 90)

I am trying to create an RcppArmadillo function that reproduces this operation:

x[is.na(x)] <- y

so that x == c(80, 2, 90, 4).

Things I've tried

After reading some documentation, I was able to write a short function that replaces the NAs in X with zeros:

Rcpp::cppFunction(
    depends = 'RcppArmadillo',
    'arma::vec f(arma::vec x) {
        x.elem(find_nonfinite(x)).zeros();
        return(x);
     }'
)

Which in fact behaves as follows:

r$> f(x)                                                                                                                                                                                               
     [,1]
[1,]    0
[2,]    2
[3,]    0
[4,]    4

I could not, however, find a one-line (or few-lines) way to do what I want. I've tried something using x.replace(), but I could never get types to properly match. I guess another way to do this would be to loop through each element y(j) and x(i) and do x(i) = y(j) if x(i) == NA_INTEGER, but that sounds like it takes way more lines than it should.


Solution

  • For visibility, here's a solution based on user2957945's comment above:

    cppFunction('
        arma::vec f2(arma::vec& x, arma::vec& y) {
            x.elem(find_nonfinite(x)) = y;
            return(x);
        }',
        depends='RcppArmadillo'
    )