Skip to content

Instantly share code, notes, and snippets.

@gtm19
Created January 4, 2020 16:14
Show Gist options
  • Save gtm19/7cbbc555809deac2ca51b4cf30af768e to your computer and use it in GitHub Desktop.
Save gtm19/7cbbc555809deac2ca51b4cf30af768e to your computer and use it in GitHub Desktop.
## 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