使用Rcpp重写R的cummin()函数并允许NA

Ben*_*Ben 7 r rcpp

我正在学习Rcpp.在这个例子中,我试图cummin()像基本R一样滚动我自己的函数cummin(),除了我希望我的版本有一个na.rm参数.这是我的尝试

cummin.cpp

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector cummin_cpp(NumericVector x, bool narm = false){
  // Given a numeric vector x, returns a vector of the 
  // same length representing the cumulative minimum value
  // if narm = true, NAs will be ignored (The result may 
  // contain NAs if the first values of x are NA.)
  // if narm = false, the resulting vector will return the 
  // cumulative min until the 1st NA value is encountered
  // at which point all subsequent entries will be NA

  if(narm){
    // Ignore NAs
    for(int i = 1; i < x.size(); i++){
      if(NumericVector::is_na(x[i]) | (x[i-1] < x[i])) x[i] = x[i-1];
    }
  } else{
    // Don't ignore NAs
    for(int i = 1; i < x.size(); i++){
      if(NumericVector::is_na(x[i-1]) | NumericVector::is_na(x[i])){
        x[i] = NA_REAL;
      } else if(x[i-1] < x[i]){
        x[i] = x[i-1];
      }
    }
  }

  return x;
}
Run Code Online (Sandbox Code Playgroud)

foo.R

library(Rcpp)
sourceCpp("cummin.cpp")

x <- c(3L, 1L, 2L)
cummin(x)  # 3 1 1
cummin_cpp(x)  # 3 1 1

class(cummin(x))  # integer
class(cummin_cpp(x))  # numeric
Run Code Online (Sandbox Code Playgroud)

我有几个问题..

  1. R的标准变量名称na.rm不是narm我所做的.但是,似乎我不能在c ++变量名中使用点.有没有办法解决这个问题,所以我可以与R的惯例保持一致?
  2. 如果用户的输入将是数字向量或整数向量,我不知道提前知道,所以我使用了Rcpp的NumericVector类型.不幸的是,如果输入是整数,则输出将转换为数字,而不像基本R的cummin()行为.人们通常如何处理这个问题?
  3. 这条线if(NumericVector::is_na(x[i]) | (x[i-1] < x[i])) x[i] = x[i-1];看起来很傻,但我不知道更好的办法.这里的建议?

F. *_*ivé 5

我会用这个:

template<typename T, int RTYPE>
Vector<RTYPE> cummin_cpp2(Vector<RTYPE> x, bool narm){

  Vector<RTYPE> res = clone(x);
  int i = 1, n = res.size();
  T na;

  if(narm){
    // Ignore NAs
    for(; i < n; i++){
      if(ISNAN(res[i]) || (res[i-1] < res[i])) res[i] = res[i-1];
    }
  } else{
    // Do not ignore NAs
    for(; i < n; i++){
      if(ISNAN(res[i-1])) {
        na = res[i-1];
        break;
      } else if(res[i-1] < res[i]){
        res[i] = res[i-1];
      }
    }
    for(; i < n; i++){
      res[i] = na;
    }
  }

  return res;
}


// [[Rcpp::export]]
SEXP cummin_cpp2(SEXP x, bool narm = false) {
  switch (TYPEOF(x)) {
  case INTSXP:  return cummin_cpp2<int, INTSXP>(x, narm);
  case REALSXP: return cummin_cpp2<double, REALSXP>(x, narm);
  default: Rcpp::stop("SEXP Type Not Supported."); 
  }
}
Run Code Online (Sandbox Code Playgroud)

试试这个:

x <- c(NA, 7, 5, 4, NA, 2, 4)
x2 <- as.integer(x)

cummin_cpp(x, narm = TRUE)
x

cummin_cpp(x2)
x2


x <- c(NA, 7, 5, 4, NA, 2, 4)
x2 <- as.integer(x)
x3 <- replace(x, is.na(x), NaN)

cummin_cpp2(x, narm = TRUE)
x

cummin_cpp2(x2)
x2

cummin_cpp2(x3)
x3
Run Code Online (Sandbox Code Playgroud)

说明:

  1. Joran的建议很好,只需将其包装在R函数中即可
  2. 约瑟夫伍德建议我使用调度员
  3. 请注意,它x是通过引用传递的,如果与您声明的类型相同,则会被修改(请参阅这2张幻灯片)
  4. 您需要处理NA以及NaN
  5. 如果为真,则可以使用||而不是|仅评估第一个条件.