[英]Skip occasional error in loop
I am aware that the "skip error in for loop" has been answered multiple times (see How to skip an error in a loop or Skip Error and Continue Function in R ). 我知道“for循环中的跳过错误”已被多次回答(参见如何跳过循环中的错误或R中的跳过错误和继续功能 )。 But all answers are complex and difficult to apply to a different situation for a novice.
但是所有答案都很复杂,很难适用于新手的不同情况。
I am performing a Gaussian histogram fitting on 100's of datasets using a piece of code. 我正在使用一段代码对100个数据集进行高斯直方图拟合。
results = list()
for(i in 1:length(T_files)){
R = Table[i][,1]
tab = data.frame(x = seq_along(R), r = R)
res = nls(R ~ k*exp(-1/2*(x-mu)^2/sigma^2), start=c(mu=15,sigma=5, k=1) , data = tab)
v = summary(res)$parameters[,"Estimate"]
fun = function(x) v[3]*exp(-1/2*(x-v[1])^2/v[2]^2)
results[[i]] = fun(seq(0, 308, 1))/max(fun_SP(seq(0, 308, 1)))/2
}
The code works on most datasets when tested on each individual. 在对每个人进行测试时,代码适用于大多数数据集。 However, the loop does not and shows the "error in nls(...): singular gradient" message.
但是,循环不会显示“nls(...)中的错误:奇异梯度”消息。 I want to skip this message and continue to the next dataset.
我想跳过此消息并继续下一个数据集。
I know that a tryCatch
function may be used, but the line containing the nls
function is complex and I have not found a way to use correctly tryCatch in this line. 我知道可以使用
tryCatch
函数,但包含nls
函数的行很复杂,我还没有找到在这一行中正确使用tryCatch的方法。 Any advice is welcome :-) 欢迎任何建议:-)
Use the function try
, it allows you save an error and then put a condition if(error==T)
then "pass to next df". 使用函数
try
,它允许你保存错误,然后输入一个条件if(error==T)
然后“传递给下一个df”。 Something like this: 像这样的东西:
error<-try(your code...)
if(class(error)!="try-error"){pass to the next one}
In yor case, maybe must be: 在你的情况下,也许必须是:
results = list()
for(i in 1:length(T_files)){
R = Table[i][,1]
tab = data.frame(x = seq_along(R), r = R)
error = try(res <- nls(R ~ k*exp(-1/2*(x-mu)^2/sigma^2), start=c(mu=15,sigma=5, k=1) , data = tab))
if(class(error)!="try-error"){
v = summary(res)$parameters[,"Estimate"]
fun = function(x) v[3]*exp(-1/2*(x-v[1])^2/v[2]^2)
results[[i]] = fun(seq(0, 308, 1))/max(fun_SP(seq(0, 308, 1)))/2
}else{
pass to next data frame (or something like that)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.