【发布时间】:2017-06-07 13:37:23
【问题描述】:
我正在尝试找到一种更快的替代方法来查找 R 中的重复项。代码的目的是将矩阵与该矩阵中的行号一起传递给 Rcpp,然后循环遍历整个矩阵以寻找匹配项排。有问题的矩阵是一个具有 1000 行和 250 列的逻辑矩阵。
听起来很简单,但下面的代码没有检测等效向量行。我不确定这是否与 equal() 函数或矩阵或向量的定义方式有关。
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::plugins]]
#include <cstddef> // std:size_t
#include <iterator> // std:begin, std::end
#include <vector> // std::vector
#include <iostream>
#include <string>
// [[Rcpp::export]]
bool dupCheckRcpp (int nVector,
LogicalMatrix bigMatrix) {
// initialize
int i, j, nrow, ncol;
nrow = bigMatrix.nrow();
ncol = bigMatrix.ncol();
LogicalVector vec(ncol); // holds vector of interest
LogicalVector vecMatrix(ncol); // temp vector for loop through bigMatrix
nVector = nVector - 1;
// copy bigMatrix data into vec based on nVector row
for ( j = 0; j < ncol; ++j ) {
vec(j) = bigMatrix(nVector,j);
}
// check loop: check vecTeam against each row in allMatrix
for (i = 0; i < nrow; ++i) {
// copy bigMatrix data into vecMatrix
for ( j = 0; j < ncol; ++j ) {
vecMatrix(j) = bigMatrix(i,j);
}
// check for equality
if (i != nVector) { // skip if nVector row
// compare vecTeam to vecMatrix
if (std::equal(vec.begin(),vec.end(),vecMatrix.begin())) {
return true;
}
}
} // close check loop
return false;
}
【问题讨论】:
-
如果你查看在矩阵上调用的
duplicated的调用堆栈,它几乎所有的时间都花在paste中,而paste已经在C 中运行。让它更快可能并不容易。 -
which(colSums(t(mat) == mat[20,]) == ncol(mat))在我的系统上大约需要 1.5 毫秒。真的太慢了吗? -
此外,如果您可以在前面计算 all,则类似
tmp = tcrossprod(mat); which((tmp == rowSums(mat)) & lower.tri(tmp), TRUE)的内容会返回 all 匹配行。并且中间矩阵的大小为1e3 * 1e3,这似乎是可管理的
标签: c++ r matrix duplicates rcpp