【问题标题】:Efficiently loop over two matrices in R using sapply使用 sapply 有效地循环 R 中的两个矩阵
【发布时间】:2017-06-01 22:46:14
【问题描述】:

我正在尝试创建一个矩阵,该矩阵从两个单独的矩阵(均为 200 x 1000,但也可以具有不同的列大小)中获取索引,并根据函数 ks.test(Kologomorov-Smirnov 测试)计算一个值。目前我已经嵌套了创建KS.mat 的 sapply 函数,但这只会使代码更清晰,而不是更快。有没有办法加快速度?

N1=100
N2=100
m=1000

set.seed(12345)
X1=matrix(rnorm(N1*m),nrow=N1)
X2=matrix(rnorm(N2*m),nrow=N2)

#Data matrix
dat = rbind(X1,X2)

#Create a matrix of permuted labels where X1 are labeled 1 and X2 are labeled 2
B=1000
label.mat=matrix(rep(rep(c(1,2),times=c(N1,N2)),B),ncol=B)
perm.mat=apply(label.mat,2,sample)

#Create matrix of KS statistics based on permuted labels and dat
KS.mat=sapply(seq(m),function(j) 
  sapply(seq(B),function(b) ks.test(dat[perm.mat[,b]==1,j],dat[perm.mat[,b]==2,j])$statistic))

【问题讨论】:

    标签: r loops sapply


    【解决方案1】:

    我不知道是否有数学方法可以降低这项任务的复杂性,但我有个好消息要告诉你!既然您用sapply 重写了您的for 循环,那么您离用parSapply 并行化它还差一步。应该就这么简单:

    require('parallel')
    cl = makeCluster(detectCores())
    clusterExport(cl, c("perm.mat","B","dat"))
    KS.mat=parSapply(cl, seq(m),function(j) 
      sapply(seq(B),function(b) ks.test(dat[perm.mat[,b]==1,j],dat[perm.mat[,b]==2,j])$statistic))
    

    预计速度会与您机器上可用的内核数量相关。

    【讨论】:

    • 太棒了!谢谢,我会尝试并报告。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 2014-10-02
    • 1970-01-01
    • 1970-01-01
    • 2012-02-21
    • 2021-05-24
    • 2012-10-02
    相关资源
    最近更新 更多