我正在测试嵌套循环。我们的想法是首先遍历i和k,将它们相加,然后循环遍历j(j必须不等于k)。循环运行了很长时间,我必须手动停止循环。由于它是一个小数据,我知道它不应该花那么长时间,但不能弄清楚它出错的地方。以下是样本数据。
test = data.frame(ID = c(1,2,3), s= c(0.4,0.3,0.3), j1 = c(0.3,0.22,0.15), j2 = c(0.11,0.58, 0.02))
这是代码:
j = 1
k = 1
firstsum = 0
tm1 <- system.time(
while (j <= nrow(test)){
while (k <= nrow(test)){
if (k == j) {
next
} else {
for (i in 3:4){
normindator = normindator + (test[j,i] * test[k, i])
denominator = denominator + test[j, i] * test[j, i]
firstsum = firstsum + norminator/denominator * test[k, 2]
k = k + 1
normindator = 0
denominator = 0
}
}
}
secondsum = 0
secondsum = secondsum + firstsum * test[j,2]
j = j + 1
k = 1
}
)
答案 0 :(得分:1)
使用next
跳过k
的增量。试试这个版本的循环
test = data.frame(ID = c(1,2,3), s= c(0.4,0.3,0.3), j1 = c(0.3,0.22,0.15), j2 = c(0.11,0.58, 0.02))
j = 1
k = 1
firstsum = 0
tm1 <- system.time(
while (j <= nrow(test)){
while (k <= nrow(test)){
if (k != j) {
for (i in 3:4){
normindator = 0
denominator = 0
normindator = normindator + (test[j,i] * test[k, i])
denominator = denominator + test[j, i] * test[j, i]
firstsum = firstsum + normindator/denominator * test[k, 2]
}
}
k = k + 1
}
secondsum = 0
secondsum = secondsum + firstsum * test[j,2]
j = j + 1
k = 1
}
)