Rcpp:如何在 rcpp 中获取可为空矩阵的行/列数

Rcpp: how to get the number of row/ column for a nullable matrix in rcpp

我发现我们不能在函数中将 .ncol().nrow() 用于类型为 Nullable<NumericMatrix> 的矩阵。一个简单的例子是:

cppFunction('int getdim(Nullable<NumericMatrix> X_mat) {
  if(X_mat.isNotNull()){
    int col_num = X_mat.ncol();
    return col_num;
  }else{
    return 0;
  }
  }')

有没有办法方便的获取相应的信息?谢谢!!!

如现有示例所示,在 'not NULL' 情况下,您 必须 实例化一个对象:

R> Rcpp::cppFunction('int getdim(Nullable<NumericMatrix> X_mat) {
+   if(X_mat.isNotNull()) {
+     NumericMatrix M(X_mat);
+     int col_num = M.ncol();
+     return col_num;
+   }else{
+     return 0;
+   }
+ }')
R> getdim(NULL)
[1] 0
R> getdim(matrix(1:4,2))
[1] 2
R>