在下面的代码中我遇到了错误:
运行时错误 while(x0tol){:缺少值需要TRUE / FALSE时出错 执行暂停
如果我注释掉循环,x0tol返回TRUE并且类逻辑。我错过了什么?提前谢谢。
a = c(1,2,2,3,3,4,5,6,6,6,8,10)
b = c(-890,1411,-1560,-2220,-2091,-2878,-3537,-3268,-3920,-4163,-5471,-5157)
data = data.frame(a,b)
tol = .0001
m = dim(data)[1]
x0 = 0
x1 = 0
x0temp = 1
x1temp = 1
alpha = 1
x0tol = TRUE
while(x0tol){
x0sum = 0
x1sum = 0
for (i in 1:m){
x0sum = x0 + x1*data[m,1] - data[m,2]
x1sum = (x0 + x1*data[m,1] - data[m,2])*data[m,1]
}
x0temp = x0 - alpha*1/m*x0sum
x1temp = x1 - alpha*1/m*x1sum
x0tol = (abs(x0 - x0temp) > tol)
x1tol = x1 - x1temp
x0 = x0temp
x1 = x1temp
class(x0tol)
x0tol
}
答案 0 :(得分:0)
由于某种原因,它假设你的while循环条件中有一个NA值。只需更改语句并创建一个带有中断的If语句就应该允许循环起作用。干杯
while(TRUE){
x0sum = 0
x1sum = 0
for (i in 1:m){
x0sum = x0 + x1*data[m,1] - data[m,2]
x1sum = (x0 + x1*data[m,1] - data[m,2])*data[m,1]
}
x0temp = x0 - alpha*1/m*x0sum
x1temp = x1 - alpha*1/m*x1sum
if (abs(x0 - x0temp) > tol){break}
x1tol = x1 - x1temp
x0 = x0temp
x1 = x1temp
class(x0tol)
x0tol
}