【发布时间】:2021-12-03 15:41:01
【问题描述】:
我在循环中运行uniroot 函数,但遇到错误并且代码停止。代码如下;
func <-function(f) -a*b/c*0.5*d*e^2 + (d/f-1)*g*sin(h*(pi/180))-i
dat <- data.frame(a = c(0.99,0.99,0.99),
b = c(0.1986572,0.1986572,0.1986572),
c = c(237.5,237.5,237.5),
d = c(1028.372, 1028.711, 1028.372),
e = c(2.46261, 2.986461, 2.46261),
f = c(-1,-1,-1),
g = c(9.8,9.8,9.8),
h = c(-54.97964, -51.65978, -54.97964),
i = c(0.03699588, -0.0375189, 0.03699588))
for(j in 1:length(dat$a)){
a <- dat$a[j]
b <- dat$b[j]
c <- dat$c[j]
d <- dat$d[j]
e <- dat$e[j]
#f: this should be solved by uniroot
g <- dat$g[j]
h <- dat$h[j]
i <- dat$i[j]
sol <- uniroot(func,c(0, 2000),extendInt = "yes")
dat$f[j] <- sol$root
print(j)
}
运行上面的代码,遇到下面的错误:
[1] 1
Error in uniroot(func, c(0, 2000), extendInt = "yes") :
no sign change found in 1000 iterations
代码停在j=1,并没有走到j=2&3。因此,dat$f显示
> dat$f
[1] 1526.566 -1.000 -1.000
我的目标是当uniroot 在给定的j 中遇到错误时,将NA 放入dat$f[j],并在最后继续循环。
如果可行,dat$f[1] 和 dat$f[3] 应该使用上述数据框具有相同的值 (=1526.566)。
请告诉我如何处理 uniroot 错误。
(这篇文章已被修改为包含可供所有人重现的代码,如suggested in my last post)
【问题讨论】:
-
是的,这回答了我的问题。非常感谢。