Aliases: try
Keywords: programming
### ** Examples ## this example will not work correctly in example(try), but ## it does work correctly if pasted in options(show.error.messages = FALSE) try(log("a")) print(.Last.value)
NULL
options(show.error.messages = TRUE) ## alternatively, print(try(log("a"), TRUE))
[1] "Error in log(\"a\") : non-numeric argument to mathematical function\n" attr(,"class") [1] "try-error" attr(,"condition") <simpleError in log("a"): non-numeric argument to mathematical function>
## run a simulation, keep only the results that worked. set.seed(123) x <- stats::rnorm(50) doit <- function(x) { x <- sample(x, replace = TRUE) if(length(unique(x)) > 30) mean(x) else stop("too few unique points") } ## alternative 1 res <- lapply(1:100, function(i) try(doit(x), TRUE)) ## alternative 2 ## Not run: ##D res <- vector("list", 100) ##D for(i in 1:100) res[[i]] <- try(doit(x), TRUE) ## End(Not run) unlist(res[sapply(res, function(x) !inherits(x, "try-error"))])
[1] 0.1038462937 0.2203698307 -0.0596661593 0.3708669961 0.0665046900 [6] 0.0792881652 0.0663761369 0.1141272652 -0.0643349711 -0.0216906885 [11] -0.1626084595 -0.0566880329 0.0886473556 0.1004842418 0.2831906261 [16] -0.0065789682 -0.1581928697 -0.1387666562 0.2048116508 0.1802423172 [21] 0.0437778643 0.0472314668 0.2720474611 -0.0164757286 0.1039084397 [26] -0.1371396827 0.0674041227 0.1104542059 -0.0134320967 -0.0601724607 [31] -0.0224327307 -0.0342157765 0.0480507372 0.0513758611 -0.0131174373 [36] 0.0470753156 0.3035483106 0.1515867000 -0.1677659486 -0.0482878061 [41] -0.1799587591 -0.1861287551 0.0845282836 -0.1096289736 0.1102887424 [46] 0.0643370194 -0.0139319224 -0.0879206273 -0.0309095587 -0.0416872956 [51] 0.2262913312 0.1147464101 0.1933621895 0.2255084914 0.0005507262 [56] 0.1285301322 0.0456429498 -0.1236476876 -0.1356975337 0.0235302138 [61] 0.1952604720 -0.0593417165 -0.0271823531 -0.1626786990 0.2038705988 [66] -0.0348928444 0.2576927806 0.2842287938 -0.1718551174 0.0904757090