【问题标题】:rcpp named numeric matrixrcpp 命名数字矩阵
【发布时间】:2016-03-05 16:47:38
【问题描述】:

使用 Rcpp,我无法找到在 C++ 代码中通过列名来寻址矩阵的方法。各种 Matrix 函数似乎没有重载,可让您按 R 中指定的名称对行或列进行寻址。我对此的用例是您有一个来自 sql 查询等的值表,其中每一列已命名。

这是我想出的明显不完整且不理想的工作:

class NamedNumericMatrix {
public:
    NamedNumericMatrix(SEXP m)
    {
      M=NumericMatrix(m);
      List dimnames = M.attr("dimnames");
      vector<string> colnames = dimnames[1];
      for(int i = 0; i<colnames.size(); i++){
        map<string, int>::iterator it = colNameIndex.find(colnames[i]);
        if(it != colNameIndex.end()){
          throw std::invalid_argument("duplicate colname found");
        }
        colNameIndex[colnames[i]] = colNameIndex.size()-1;
      }
    }
    double GetValue(int row, string col){
      map<string, int>::iterator it = colNameIndex.find(col);
      if(it == colNameIndex.end()){
        throw std::invalid_argument("col name not found");
      }
      return M(row, it->second);
    }
  int nrow(){
    return M.nrow();
  }
  int ncol(){
    return M.ncol();
  }
private:
    NumericMatrix M;
    map<string, int> colNameIndex;
};

我的问题是,有没有更简单的方法来使用 Rcpp 做到这一点?

【问题讨论】:

    标签: c++ r matrix rcpp


    【解决方案1】:

    只需使用返回字符向量的colnames()

    R> cppFunction("int showme(NumericMatrix M) { print(colnames(M)); return 0; }")
    R> showme(matrix(1:9,3,dimnames=list(NULL, c("a1", "b2", "c3"))))
    [1] "a1" "b2" "c3"
    [1] 0
    R> 
    

    哦,抱歉,重新阅读:您的意思是 index 的名称?我们主要将矩阵视为数字对象。您可以按名称索引ListDataFrame。对于矩阵,您可能已经用上述内容回答了您的问题。

    【讨论】:

    • 这很有道理,可能我将这种类型的数据存储在DataFrame中会更合适
    • 我也这么认为。从 db 中,您还可能会得到不同的类型,这些类型并不总是适合矩阵。
    猜你喜欢
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多