妥善的解决办法是完全正确的。 但是,如果你有大的矩阵,你可能会想根据再入侵来尝试其他东西。 如果你工作一栏,你可以缩短计算时间,排除与第一个职位对应的一切:
fastercheck <- function(x,matrix){
nc <- ncol(matrix)
rec.check <- function(r,i,id){
id[id] <- matrix[id,i] %in% r[i]
if(i<nc & any(id)) rec.check(r,i+1,id) else any(id)
}
apply(x,1,rec.check,1,rep(TRUE,nrow(matrix)))
}
比较:
> set.seed(100)
> x <- matrix(runif(1e6),ncol=10)
> a <- matrix(runif(300),ncol=10)
> a[c(3,7,9,15),] <- x[c(1000,48213,867,20459),]
> system.time(res1 <- a %inm% x)
user system elapsed
31.16 0.14 31.50
> system.time(res2 <- fastercheck(a,x))
user system elapsed
0.37 0.00 0.38
> identical(res1, res2)
[1] TRUE
> which(res2)
[1] 3 7 9 15
EDIT:
I checked the accepted answer just for fun. Performs better than the double apply ( as you get rid of the inner loop), but recursion still rules! ;-)
> system.time(apply(a, 1, paste, collapse="$$") %in%
+ apply(x, 1, paste, collapse="$$"))
user system elapsed
6.40 0.01 6.41