【问题标题】:Using Rcpp sugar on data.frame names在 data.frame 名称上使用 Rcpp 糖
【发布时间】:2021-03-27 23:47:03
【问题描述】:

我想将 data.frame 作为参数传递给带有可选列的 Rcpp 函数。然后,c++ 函数需要测试列是否存在。如果我使用以下示例中的糖函数any,则会出现编译错误。

cppFunction(
  'double test(DataFrame test_data) {
      double x=NA_REAL;
      CharacterVector colnames = CharacterVector::create("foo");
      CharacterVector df_names = test_data.names();
      if (any(df_names == colnames)) x = 1.0;
      return(x);
    }')

不完整类型类Rcpp::sugar::forbidden_​​conversion`的使用无效

我知道我可以在循环中一一测试字符值,就像这样(按预期工作):

cppFunction(
  'double test(DataFrame test_data) {
      double x=NA_REAL;
      CharacterVector colnames = CharacterVector::create("foo");
      CharacterVector df_names = test_data.names();
      for (int i=0; i<df_names.length(); i++) {
        if (df_names[i] == colnames[i]) x = 1.0;
      }
      return(x);
    }')
test(data.frame(bar=3))
# [1] NA
test(data.frame(foo=3))
# [1] 1

但是,如果可能的话,我想使用矢量化的“糖”版本。我做错了什么,我该怎么做?

【问题讨论】:

    标签: r rcpp


    【解决方案1】:

    你可以加is_trueto return a boolean:

    library(Rcpp)
    cppFunction(
      'double test(DataFrame test_data) {
          double x=NA_REAL;
          CharacterVector colnames = CharacterVector::create("foo");
          CharacterVector df_names = test_data.names();
          if (is_true(any(df_names == colnames))) x = 1.0;
          return(x);
        }')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-01-08
      • 1970-01-01
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多