Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Manipulating NumericMatrix in Rcpp

Tags:

r

rcpp

I'm new with Rcpp. I have read Advanced R by Hadley Wickham and all Rcpp vignettes but i can't figure how to manipulate NumericMatrix objects.

Is there any simple way to do things 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

other than looping on rows and columns and setting the value of each mat[i,j] ?


Edit3 : Ok let's try again.

Here's 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've pointed my problem in comments. In the first one (//**1) i have to write two loops to set first row and first column. What i'm asking is : is there any simpler way to do it, like we can do in R?

This is the same issue i have pointed out in my code's comments.

like image 578
throwic Avatar asked Dec 02 '15 14:12

throwic


1 Answers

Technically yes, though it's only a sugar IIRC. 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
like image 93
tonytonov Avatar answered Oct 17 '22 09:10

tonytonov