purrr and failure in R
safely and possibly turn an error into a value you can inspect.
library(purrr)
library(dplyr)
parse_tpm <- function(text) {
value <- suppressWarnings(as.numeric(text))
if (is.na(value)) stop("not a number: ", text)
value
}
safe_parse <- safely(parse_tpm)
results <- map(c("96", "fast", "104"), safe_parse)
print(map_lgl(results, ~ is.null(.x$error)))
print(compact(map(results, "result")) |> unlist())
maybe_parse <- possibly(parse_tpm, otherwise = NA_real_)
print(map_dbl(c("96", "fast"), maybe_parse))
frames <- map(1:2, ~ tibble(n = .x, squared = .x^2))
print(list_rbind(frames))
How it works
safelyreturns a list of result and error, never throwing.possiblysubstitutes a default instead.list_rbindstacks the successful results.
Keywords and builtins used here
ccompactfunctioniflibrarylist_rbindmapmap_dblmap_lglpossiblyprintsafelystopsuppressWarningstibbleunlist
The run, in numbers
- Lines
- 19
- Characters to type
- 522
- Tokens
- 151
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 86 seconds.
Step 3 of 4 in purrr, step 3 of 10 in Functional & text tools.