如何加快R中两个矩阵子集的比较

时间:2016-07-13 16:49:20

标签: r matrix vectorization

我有一个矩阵R,比如20x20和一个矩阵s_mat,比如400x2。我想比较(存储在h.help)矩阵2x1的大小R的每个子向量到s_mat的每一行。使用for循环,如下面的代码,需要太长时间。有什么办法可以避免这些循环吗?因为对于较大的矩阵,它需要太长时间。非常感谢!

library(gtools)
R=matrix(sample(1:20,400, replace=TRUE), ncol=20, nrow=20)
l=2
s_mat = permutations(nrow(R), l, repeats.allowed=TRUE) 
F = numeric()
F_perm = data.frame(matrix(NA,ncol=nrow(R)^l,nrow=nrow(R)-l+1)) 
  for (perm in 1:nrow(s_mat))
  {
    s = s_mat[perm,]
    for (k in 0:(nrow(R)-l))  
    {
      h = rep (TRUE, ncol(R)) 
      for (j in 1:ncol(R))   
      {
        h.help = R[(k+1):(k+l),j] <= s
        if (sum(h.help)!=l) h[j]=FALSE
      } 
      F[k+1] = sum(h)/ncol(R)
    }
    F_perm[perm] = F
  }

1 个答案:

答案 0 :(得分:0)

我认为这将完成这项工作:

set.seed(1L);
NV <- 20L; R.NR <- 20L; R.NC <- 20L; NP <- 2L;
R <- matrix(sample(NV,R.NR*R.NC,T),R.NR);
s_mat <- unname(as.matrix(do.call(expand.grid,rep(list(seq_len(NV)),NP))));
F_perm <- matrix(NA_real_,R.NR-NP+1L,nrow(s_mat));
for (sri in seq_len(nrow(s_mat))) {
    s <- s_mat[sri,];
    F_perm[,sri] <- rowSums(Reduce(`&`,Map(function(e,i) R[i:(nrow(R)-length(s)+i),]<=e,s,seq_along(s))))/ncol(R);
}; ## end for