首页 > 解决方案 > 我的 While 循环没有在 R 中完成,我怎么知道问题出在哪里?

问题描述

我正在尝试在具有 70,000++ 行的数据帧上运行 while 循环。我已经在部分数据框上尝试了我的代码,并且效果很好。但我现在已经等了 5 分钟了,什么也没发生。所以我相信这是因为数据集很大。有什么办法可以加快这个过程吗?这是我的代码

library(arrangements)
assignments <- permutations(c(0,1), 22, freq=c(11,11))
results<- data.frame()


i = 1
 #choose row
while(i < nrow(assignments)){
  Y1_sum = 0
  Y0_sum = 0
# choose columns
  j = 1

  while (j <= 22){
    n = assignments[i, j]
    
    if(n == 1){
      Y1 = potential_outcome[j,4]
      Y1_sum <- Y1_sum + Y1
    } else if(n == 0){
      Y0 = potential_outcome[j, 3]
      Y0_sum <- Y0_sum + Y0
    }
    j <- j + 1
  }

  result = abs(Y1_sum/11 - Y0_sum /11)
  results <-  rbind(results, result)
  i <- i + 1
}

这里的潜在结果是一个看起来像这样的数据框

potential_outcome

在此处输入图像描述

标签: rcombinations

解决方案


使用rbind在循环内增长数据框是导致缓慢的原因。它会产生大量的计算开销。我相信这会得到你想要的结果:

# Test data
potential_outcomes <- data.frame(Yi.0 = replicate(22, runif(1, 1, 15)),
                                 Yi.1 = replicate(22, runif(1, 1, 15)))

# If n == 1
Y1 <- assignments %*% potential_outcomes[, "Yi.1"]

# If n == 0 (invert zeros and ones)
Y0 <- (1 - assignments) %*% potential_outcomes[, "Yi.0"]

# Results
results <- abs(Y1 - Y0) / 11

矩阵乘法%*%返回每个赋值行 * potential_outcomes 向量的总和。


推荐阅读