Optimization has not converged in R -
i have function estimates 2 moments of truncated gaussian distribution using maximum likelihood method. in database, not obtain results converge. put warning see how many of them are.
then tried erase them, using trycatch
function seems don't know how use properly.
does have idea ?
here code :
df=as.data.frame(matrix(0,1000,2)) df$v1=runif(nrow(df),0,1) df$v2=sample(c(1:10),nrow(df), replace=true) library(truncnorm) f <- function(d) # d vector { trycatch( { f2 <- function(x) -sum(log(dtruncnorm(d, a=0, b=1, mean = x[1], sd = x[2]))) res <- optim(par=c(mean(d),sd(d)),fn=f2) if(res$convergence!=0) warning("optimization has not converged") return(list(res1=res$par[1],res2=res$par[2]^2)) }, error = function(error) {return()} ) } res1=tapply(df$v1, df$v2, function(x) f(x)$res1)
so idea "clean" res1
deleting values have not converged.
best regards.
here small example of how trycatch
works. need run expression within trycatch
, @ result. if expression encounters error (or warning), can adjust workflow. point is, though warning or error produced, life goes on , program doesn't stop.
my.list <- vector("list", 15) set.seed(357) (i in 1:length(my.list)) { result <- trycatch( { if (runif(1) > 0.5) { stop("more 0.5") } else { 42 } }, error = function(e) e ) # bit catches result , manipulates further (output nas or whathaveyou) if (!is.numeric(result)) { my.list[[i]] <- "failed converge, coerce na" } else { my.list[[i]] <- result } } my.list [[1]] [1] 42 [[2]] [1] 42 [[3]] [1] 42 [[4]] [1] 42 [[5]] [1] "failed converge, coerce na" [[6]] [1] 42 [[7]] [1] "failed converge, coerce na" [[8]] [1] "failed converge, coerce na" [[9]] [1] "failed converge, coerce na" [[10]] [1] "failed converge, coerce na" [[11]] [1] "failed converge, coerce na" [[12]] [1] "failed converge, coerce na" [[13]] [1] 42 [[14]] [1] 42 [[15]] [1] "failed converge, coerce na"
if expression doesn't evaluate (it encounters stop
) error message returned. can substitute own function outputs data.frame nas or has other desired behavior.
# custom function produces custom output myfun <- function(x) { na } set.seed(357) (i in 1:length(my.list)) { result <- trycatch({ if (runif(1) > 0.5) { stop("more 0.5") } else { 42 } }, error = myfun ) my.list[[i]] <- result } my.list [[1]] [1] 42 [[2]] [1] 42 [[3]] [1] 42 [[4]] [1] 42 [[5]] [1] na [[6]] [1] 42 [[7]] [1] na [[8]] [1] na [[9]] [1] na [[10]] [1] na [[11]] [1] na [[12]] [1] na [[13]] [1] 42 [[14]] [1] 42 [[15]] [1] na
Comments
Post a Comment