我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 错误。
(这篇文章被修改为包含可供所有人重现的代码,正如我在上一篇文章中所建议的那样)