r - 如何避免矩阵计算中的双for循环

标签 r for-loop double

我的函数可以工作,但是当我有大数据集时它会很慢。

我该怎么做才能加快速度?我知道我们应该避免使用双 for 循环,但我不知道为什么。

非常感谢!

    n <- 3
    wr <- c(0.9, 0.6, 0.5)
    mat <- matrix(1:9, nrow=3, byrow=TRUE)
    
    tmp    <- matrix(nrow = n, ncol = n)
    out   <- rep(0, n)
    
    colsum <- apply(mat, 2, sum)
    
    for (i in 1:n) {
      for (j in 1:n) {
        tmp[i, j] <- (mat[i, j]/ colsum[j])*(1-wr[j])
      }
    }
    
    for (i in 1:n) {
      out[i] <- 1-sum(tmp[1:n,i])
    }

最佳答案

试试这个:

n <- 3
wr <- c(0.9, 0.6, 0.5)
mat <- matrix(1:9, nrow=3, byrow=TRUE)

tmp    <- matrix(nrow = n, ncol = n)
out   <- rep(0, n)

colsum <- apply(mat, 2, sum)

for (i in 1:n) {
  for (j in 1:n) {
    tmp[i, j] <- (mat[i, j]/ colsum[j])*(1-wr[j])
  }
}

for (i in 1:n) {
  out[i] <- 1-sum(tmp[1:n,i])
}

# alternatively:
tmp2 = t(t(mat) / colsum * (1-wr))
out2 = 1 - colSums(tmp)
> tmp
            [,1]       [,2]       [,3]
[1,] 0.008333333 0.05333333 0.08333333
[2,] 0.033333333 0.13333333 0.16666667
[3,] 0.058333333 0.21333333 0.25000000
> out
[1] 0.9 0.6 0.5
> tmp2
            [,1]       [,2]       [,3]
[1,] 0.008333333 0.05333333 0.08333333
[2,] 0.033333333 0.13333333 0.16666667
[3,] 0.058333333 0.21333333 0.25000000
> out2
[1] 0.9 0.6 0.5

关于r - 如何避免矩阵计算中的双for循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62729526/

相关文章:

python - 在 Python 中使用 for 循环垂直翻转图像

java - 为什么这个 for 循环不起作用?

r - Cowplot 使 ggplot2 主题消失/如何查看当前的 ggplot2 主题,并恢复默认?

r - nearPoints 无法从 Shiny 的坐标信息中自动推断出 `xvar`

email - 发送邮件R : Submit encoded message to local SMTP server

c++ - 编写多个 'for' 循环的干净方法

ios - 无法在 iOS 中的数组上声明追加命令

java - 双减 int 给出意想不到的结果

c++ - 断言 double 可以放入 int

r - 如何在表格行中选择大于 x 的值