Numeric Matrix Manipulation in Rcpp

I am new to rcpp. I read Advanced R by Hadley Wickham and all the Rcpp vignettes, but I can't figure out how to manipulate NumericMatrix objects.

Is there an easy way to do something like this R code

 mat <- matrix(1:9,3,3) v <- matrix(2,2,2) mat[1,] <- NA mat[,3] <- 0.5 mat[2:3,2:3] <- v 

except looping through rows and columns and setting the values โ€‹โ€‹of each mat[i,j] ?


Edit3: Ok try again.

Here is my cpp file:

 #include <Rcpp.h> using namespace Rcpp; // [[Rcpp::export]] NumericMatrix lissage_incapC(NumericMatrix mat) { // INIT NumericMatrix x(mat.nrow()+1,mat.ncol()+1); NumericMatrix out(mat.nrow(),mat.ncol()); // Here i want to set x first row and first column to NA_REAL //**1 for(int i=0; i<x.nrow(); i++){ for(int j=0; j<x.ncol(); j++){ if(i==0 || j==0) x(i,j) = NA_REAL; x(i,j) = mat(i-1,j-1); } } for(int i=8; i<x.nrow()-1; i++){ for(int j=1; j<x.ncol()-1; j++){ NumericMatrix y = x(Range(i-1,i+1),Range(j-1,j+1)); y(1,1) = NA_REAL; if((i == 8) & (j>1)) y.row(0) = NumericVector::get_na(); //problem here out(i,j-1) = 1/2*x(i,j) + 1/2 * mean(na_omit(y)); } } out(_,out.ncol()) = 0.5; // Problem here out(Range(0,7),_) = out(8,_); // Problem here return out; } 

I pointed out my problem in the comments. In the first (// ** 1) I need to write two loops to set the first row and first column. I ask: is there an easier way to do this, how can we do in R?

This is the same issue that I mentioned in the comments on the code.

+7
r rcpp
source share
1 answer

Technically yes, although it is only IIRC sugar. Here's a short demo:

 library(inline) src <- ' Rcpp::NumericMatrix Am(A); NumericVector na_vec(Am.ncol(), NA_REAL); Am(0, _) = na_vec; Am(_, 0) = na_vec; return Am; ' f <- cxxfunction(signature(A = "numeric"), body = src, plugin = "Rcpp") f(matrix(1, 3, 3)) # [,1] [,2] [,3] #[1,] NA NA NA #[2,] NA 1 1 #[3,] NA 1 1 
+1
source share

All Articles