I am a newbie to Rcpp (and a newbie to C++). I wrote a code using an example code here https://gist.github.com/kevinushey/4561281 to calculate row/col max/mix for matrices as follows:

#include <Rcpp.h>
using namespace Rcpp;

template <class T>
inline double do_max(T& x) {
  return max(x);
}

template <class T>
inline double do_min(T& x) {
  return min(x);
}

NumericVector colMaxsCpp(NumericMatrix& x) {
  int nRows = x.nrow();
  NumericVector out = no_init(nRows);

  for (int i=0; i<nRows;i++) {
    NumericMatrix::Row tmp = x(i,_);
    out[i]=do_max(tmp);
  }

  return out;
}

NumericVector colMinsCpp(NumericMatrix& x) {
  int nRows = x.nrow();
  NumericVector out = no_init(nRows);

  for (int i=0; i<nRows;i++) {
    NumericMatrix::Row tmp = x(i,_);
    out[i]=do_min(tmp);
  }

  return out;
}

NumericVector rowMaxsCpp(NumericMatrix& x) {
  int nCols = x.ncol();
  NumericVector out = no_init(nCols);

  for (int i=0; i<nCols;i++) {
    NumericMatrix::Column tmp = x(_,i);
    out[i]=do_max(tmp);
  }

  return out;
}

NumericVector rowMinsCpp(NumericMatrix& x) {
  int nCols = x.ncol();
  NumericVector out = no_init(nCols);

  for (int i=0; i<nCols;i++) {
    NumericMatrix::Column tmp = x(_,i);
    out[i]=do_min(tmp);
  }

  return out;
}

// [[Rcpp::export]]
NumericVector Max(NumericMatrix x, int dim) {
  if (dim==1) {
    return rowMaxsCpp(x);
  } else if (dim==2) {
    return colMaxsCpp(x);
  }
}

// [[Rcpp::export]]
NumericVector Min(NumericMatrix x, int dim) {
  if (dim==1) {
    return rowMinsCpp(x);
  } else if (dim==2) {
    return colMinsCpp(x);
  }
}

I want to modify to code to handle NA in the do_min and do_max functions. The do_min and do_max functions use a template of a class.

I read on the web about NA_REAL and NA_INTEGER but these are specific to classes.

(a) Is there any generic NA available for a template of a class (such as in the example above)?

(b) Also, is there any function available that I can subset a variable x to only use non-NA elements, e.g. equivalent of max(x[!is.na(x)]) or min(x[!is.na(x)]) in R ?

(c) Finally, the code above has been written to handle a numeric matrix, but it seems to work even when an integer matrix has been supplied (albeit the output is converted to numeric). Why is this so?

有帮助吗?

解决方案

Quick ones:

a) Yes, there are but I am not sure they are vectorised. But some templated NA traits were added.

b) Yes as e.g. in

R> cppFunction('double mymax(NumericVector x) { \
                   IntegerVector x2 = wrap(na_omit(x)); \
                   return max(x2);}')
R> mymax(c(1L, 2L, NA, 4L))
[1] 4
R> 

c) Integer always gets 'cast up' to Numeric at the cost of a copy.

@Roland already hinted at na_omit. In b), somehow I need to help with a wrap() to generate an intermediate SEXP object.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top