當我學習Rcpp類/數據結構時遇到了一個新手問題:是否有成員函數來刪除類Rcpp::NumericMatrix
的對象的行/列? (或其他類型type **Matrix
- 我假設它是一個模板類)?Rcpp NumericMatrix - 如何擦除行/列?
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;
}')
如果這種類型的成員函數不存在,那麼這個怎麼辦?
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;
}')
或者我們希望刪除一組行/列:
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;
}')
我回答了類似的問題[這裏](http://stackoverflow.com/questions/33119163/rcpp-eliminating (我認爲)將你的兩個目標組合成一個函數。如果是這樣,您應該可以輕鬆地將其分別調整爲兩個單獨的行和列消除函數。 – nrussell
@nrussell - 謝謝,我會去看看 –