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.
r rcpp
throwic
source share