代码之家  ›  专栏  ›  技术社区  ›  dww Jarretinha

使用Rcpp糖数据框姓名

  •  0
  • dww Jarretinha  · 技术社区  · 4 年前

    我想通过考试数据框作为带有可选列的Rcpp函数的参数。然后,c++函数需要测试这些列是否存在。如果我使用sugar函数 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::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
    

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

    1 回复  |  直到 4 年前
        1
  •  3
  •   Waldi    4 年前

    你可以加上 is_true to 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);
        }')