请考虑以下CPP函数

// [[Rcpp::exp或t]]
int timesTwo(int x) {
  return x * 2;
}

如果我在这个函数中输入了一个错误类型的对象(例如"字符"),显然,它将无法工作并显示此错误消息 Err或: Not compatible with requested type: [type=character; target=integer].

然而,我想让它变得更有信息性,例如

Err或 in timesTwo(int x)
Err或: Not compatible with requested type: [type=character; target=integer].

Err或 in the parameter x of timesTwo(int x)
Err或: Not compatible with requested type: [type=character; target=integer].

我想知道我怎样才能在CPP中做到这一点?

推荐答案

有两种显而易见的方法来处理这一问题.第一种方法是通过R中的包装器调用cpp函数,该包装器预先执行类型判断.例如:

Rcpp::cppFunction('
  int times_two_cpp(int x) {
    return x * 2;
  }')

timesTwo <- function(x) {
  if(!is.integer(x)) stop("'x' should be an integer, not ", typeof(x))
  times_two_cpp(x)
}

经过测试,我们有:

timesTwo(5L)
#> [1] 10

timesTwo('hello')
#> Error in timesTwo("hello") : 'x' should be an integer, not character

第二种 Select 是允许您的C++函数接受任何R对象,并在内部进行类型判断.这需要对R内部 struct 有一些了解

Rcpp::cppFunction('
  Rcpp::IntegerVector timestwo(SEXP x) {
    if(TYPEOF(x) != INTSXP) {
     Rcpp::stop("in the parameter x of timesTwo - x is not an integer");
    }
    Rcpp::IntegerVector result(x);
    return result * 2;
   }
')

导致

timestwo(5L)
#> [1] 10

timestwo('hello')
#> Error: in the parameter x of timesTwo - x is not an integer

R相关问答推荐

卸载安装了BRM的模型发出的警告

无法将传奇添加到cowplot多情节中

咕噜中的元素列表:map

从gtsummary包中使用tBL_strata()和tBL_summary()时删除变量标签

在数学中正确显示摄氏度、开氏度或华氏度

如何将移除事件分配给动态创建的按钮?

如何在R中对深度嵌套的tibbles中的非空连续行求和?

如何使用tryCatch执行语句并忽略警告?

如何将R中数据帧中的任何Nas替换为最后4个值

仅在Facet_WRAP()中的相应方面包含geom_abline()

按多列统计频次

正在导出默认的RStudio主题,还是设置括号 colored颜色 ?

将工作目录子文件夹中的文件批量重命名为顺序

创建在文本字符串中发现两个不同关键字的实例的数据框

有没有办法通过str_Detect()或其他字符串匹配函数来连接两个长度不等的数据帧?

使用geom_sf跨越日期线时的闭合边界

R-找出存在其他变量的各种大小的所有组合

R将函数参数传递给ggploy

Ggplot2:添加更多特定 colored颜色 的线条

R:水平旋转图