Created
January 4, 2020 16:14
-
-
Save gtm19/7cbbc555809deac2ca51b4cf30af768e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## A short function which is effectively a wrapper around lapply, where the function is reattempted on failure | |
## a set number of times | |
repply <- function(X, FUN, ..., .max_retry = 3) { | |
init <- lapply(X, function(x) try(FUN(x), silent = TRUE), ...) | |
n <- 1 | |
while(n <= .max_retry) { | |
errors <- which(sapply(init, class) == "try-error") | |
if(length(errors) == 0) return(init) | |
init[errors] <- lapply(X[errors], function(x) try(FUN(x), silent = TRUE), ...) | |
n <- n + 1 | |
} | |
return(init) | |
} | |
# Example ----------------------------------------------------------------- | |
error_sometimes <- function(numbers, p = 0.3) { | |
if(runif(1) < p) stop("error") | |
mean(numbers) | |
} | |
num_list <- | |
list( | |
rnorm(100), | |
rnorm(100), | |
rnorm(100), | |
rnorm(100), | |
rnorm(100) | |
) | |
repply(X = num_list, error_sometimes) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment