问题描述
我学习Rcpp类/数据结构时遇到一个新手问题:是否存在一个成员函数来擦除类 Rcpp :: NumericMatrix
的对象的行/列?(或其他类型的类型**矩阵
-我假设它是模板类)?
A novice question as I learn the Rcpp classes / data structures: Is there a member function to erase a row / column for an object of class Rcpp::NumericMatrix
? (Or other types of type **Matrix
-- I'm assuming it's a template class)?
library(Rcpp)
cppFunction('
NumericMatrix sub1 {NumericMatrix x, int& rowID, int& colID) {
// let's assume separate functions for rowID or colID
// but for the example case here
x.row(rowID).erase(); // ??? does this type of member function exist?
x.col(colID).erase(); // ???
return x;
}')
如果这种类型的成员函数不存在,怎么办?
If this type of member function doesn't exist, how about this?
cppFunction('NumericMatrix row_erase (NumericMatrix& x, int& rowID) {
// a similar function would exist for removing a column.
NumericMatrix x2(Dimension(x.nrow()-1, x.ncol());
int iter = 0; // possibly make this a pointer?
for (int i = 0; i < x.nrow(); i++) {
if (i != rowID) {
x2.row(iter) = x.row(i);
iter++;
}
}
return x2;
}')
或者我们希望删除一组行/列:
Or perhaps we wish to remove a set of rows/columns:
cppFunction('NumericMatrix row_erase (NumericMatrix& x, IntegerVector& rowID) {
// a similar function would exist for removing a column.
rowID = rowID.sort();
NumericMatrix x2(Dimension(x.nrow()- rowID.size(), x.ncol());
int iter = 0; // possibly make this a pointer?
int del = 1; // to count deleted elements
for (int i = 0; i < x.nrow(); i++) {
if (i != rowID[del - 1])
x2.row(iter) = x.row(i);
iter++;
} else {
del++;
}
}
return x2;
}')
推荐答案
是的,这两种方法都可以工作(上面已修正我的错别字).我尝试将 int iter
替换为 Rcpp :: NumericMatrix :: iterator iter
时遇到转换错误.对此有任何解决办法吗?
Yes, both of these do work (fixing my typos above). I got a conversion error trying to replace int iter
with Rcpp::NumericMatrix::iterator iter
though. Any fix for this?
请注意,我们不需要 row_erase(NumericMatrix& x,int& ref)
,因为这是 row_erase(NumericMatrix& x,IntegerVector& ref)
的特例>.
Note that we do not need the row_erase(NumericMatrix& x, int& ref)
since this is a special case of row_erase(NumericMatrix& x, IntegerVector& ref)
.
NumericMatrix row_erase (NumericMatrix& x, IntegerVector& rowID) {
rowID = rowID.sort();
NumericMatrix x2(Dimension(x.nrow()- rowID.size(), x.ncol()));
int iter = 0;
int del = 1; // to count deleted elements
for (int i = 0; i < x.nrow(); i++) {
if (i != rowID[del - 1]) {
x2.row(iter) = x.row(i);
iter++;
} else {
del++;
}
}
return x2;
}
NumericMatrix col_erase (NumericMatrix& x, IntegerVector& colID) {
colID = colID.sort();
NumericMatrix x2(Dimension(x.nrow(), x.ncol()- colID.size()));
int iter = 0;
int del = 1;
for (int i = 0; i < x.ncol(); i++) {
if (i != colID[del - 1]) {
x2.col(iter) = x.column(i);
iter++;
} else {
del++;
}
}
return x2;
}
这篇关于RCPP NumericMatrix-如何删除行/列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!