Amirhossein
Amirhossein

Reputation: 37

cannot convert 'SEXP' to 'Rcpp::traits::input_parameter<double>

When I want to run following cpp code

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]

void print_mat(double *Mat, int nbLig, int nbCol) {

 int i, j;

 for (i = 0; i < nbLig; i++) {

  for (j = 0; j < nbCol; j++)

    printf("%f ", *(Mat + (nbCol * i) + j));

    putchar('\n');
  }
}

By Rcpp and sourceCpp command

I see

cannot convert 'Rcpp::traits::input_parameter::type {aka Rcpp::InputParameter}' to 'double*' for argument '1' to 'void print_mat(double*, int, int)' print_mat(*Mat, nbLig, nbCol)

How remove this error

Upvotes: 2

Views: 1038

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368499

Briefly:

  • your interface was all wrong, that is not how we pass matrices from R; see the numerous posted examples and documentation
  • with that, matrix access was wrong
  • use Rprintf() to print per Writing R Extensions

Hence a need for a repaired version:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
void print_mat(NumericMatrix Mat) {
  int nbLig = Mat.nrow(), nbCol = Mat.ncol();
  int i, j;
  for (i = 0; i < nbLig; i++) {
    for (j = 0; j < nbCol; j++)
      Rprintf("%f ", Mat(i,j));
    Rprintf("\n");
  }
}

/*** R
print_mat(matrix(1:9,3))
*/

where I also included an example use. Pulling that into R yields

R> sourceCpp("/tmp/foomat.cpp")

R> print_mat(matrix(1:9,3))
1.000000 4.000000 7.000000 
2.000000 5.000000 8.000000 
3.000000 6.000000 9.000000 
R> 

Needless to say, you could also get this via a single command:

// [[Rcpp::export]]
void print_mat2(NumericMatrix Mat) {
  print(Mat);
}

which give you row and column headers as in R:

R> print_mat2(matrix(1:9,3))
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9
R> 

Upvotes: 4

Related Questions