Last active
December 7, 2016 21:03
-
-
Save petermeissner/4a36d7187617ff78682ea6ab552600b5 to your computer and use it in GitHub Desktop.
the most awesome purrr feature?
This file contains hidden or 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
# capturing failure with default values | |
library(purrr) | |
# a faulty function | |
f <- function(x){ | |
# some nasty error occuring once in a while | |
if( x %% 2 == 0 ){ | |
stop("HAHA!") | |
} | |
# what should be returned | |
return("ok") | |
} | |
# lets make f() save again | |
f_save <- safely(f, otherwise = "error") | |
f_poss <- possibly(f, otherwise = "error") | |
# failing | |
vapply(1:5, f, "") | |
# capturing failure with handy defaults | |
lapply(1:5, f_save) | |
# processing results and status | |
f_results <- lapply(1:5, f_save) | |
f_results_df <- | |
data.frame( | |
value = f_results %>% vapply( function(x){ x$result }, character(1) ), | |
error = f_results %>% vapply( function(x){ !is.null(x$error) }, logical(1)), | |
error_message = | |
f_results %>% | |
vapply( function(x){tmp <- x$error$message; if(is.null(tmp)){""}else{tmp}}, character(1)), | |
stringsAsFactors = (HELLNO <- FALSE) | |
) | |
# Just give me the results - would you! | |
vapply(1:5, f_poss, "") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment