# c ++: linearly interpolates the NA values ​​in Rcpp :: NumericVector

I'm trying to fill in the missing values ​​with linearly interpolated values ​​in a `Rcpp :: NumericVector` – Leave initial and final NA values ​​in place.

The desired output is below:

``````R> x <- c(NA, NA, NA, 1:4, NA, 6:8, NA, 10, NA, NA, NA)
R> naLinInt (x)
R> [1] NA NA NA 1 2 3 4 5 6 7 8 9 10 NA NA NA
``````

I have implemented it through the following information, but since I am very new to C ++, I would greatly benefit from some help to understand how to do it better.

I feel that I really made my way through this, in particular, I suspect that I have used the pointers too much and that there is a better way to do this type of indexing and compensation.

``````#include

//[[Rcpp::export]]Rcpp :: NumericVector naLinInt (Rcpp :: NumericVector x) {
// This function interpolates linearly between the NA values

Rcpp :: Rcout << "We start with:" << std :: endl << x << std :: endl;

double * it1 = x.begin ();
double * it2 = x.begin ();
step int = 0;

it1 ++;

while (it1 <x.end ()) {
if (Rcpp :: NumericVector :: is_na (* it1)) {
if (Rcpp :: NumericVector :: is_na (* (it1 - 1))) {
it1 ++;
continue;
} else {
it2 = it1;
step = 0;
while (it2 <x.end () && Rcpp :: NumericVector :: is_na (* it2)) {
step ++;
it2 ++;
}
if (it2 == x.end ()) break;
// step through the missing values ​​and replace
for (int j = 0; j <step; j ++) {
* it1 = * (it1 - 1) + (* it2 - * (it1 - 1)) / (step + 1 - j);
it1 ++;
}
it1 = it2 + 1;
}
} else {
it1 ++;
}
}

returns x;
}
``````