【发布时间】: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 做到这一点?
【问题讨论】: