r - 我的 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
解决方案
使用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 向量的总和。
推荐阅读
- docker - Docker 构建会丢失在 RUN 序列中完成的所有内容
- javascript - 如何使用 dotenv 在脚本 src 中隐藏 api 键
- python - X的N次方的Python分而治之的实现
- javascript - MySQL - GROUP BY、JSON、LIMIT 5 等
- javascript - 我的 Gatsby 项目是否存在 React 的补液问题?
- scala - 在Scala中使用带有Set类型的while和for循环之间的区别
- sql - 在 SQL Server 行中存储大于 8kB 的数据是不好的做法吗?
- java - 如何成功实现从活动迁移到片段的 viewpager 和 recyclerView
- excel - 合并文件夹中的所有工作簿并移动到子文件夹
- php - 从 PHP 中的下拉列表中过滤搜索结果