Brief explanation
- See how a
for loop and a purrr::map function work with an input whose elements are problematic.
- For more information, visit an Advanced R webpage.
Workflow
- Step 1: Load a library to your
R session.
library(tidyverse)
- Step 2: Define a function that handles errors.
test_function <- function(x){
tryCatch(
log(x), # your function body
error = function(c){return(NA)} # action you want to see if an error occurs
)
}
- Step 3: Define a list whose elements vary from numeric, character, negative integer, zero, to missing.
test_list <- list(5, "a", -1, 0, NA)
- Step 4: Run a
for loop to see if it works with problematic list elements.
output <- for (i in 1:5){
log(test_list[[i]])
}
output
# Error in log(test_list[[i]]) :
# non-numeric argument to mathematical function
- Step 5: Create a list with
log and test_function.
map(test_list, log)
# Error in .Primitive("log")(x, base) : non-numeric argument to mathematical function
map(test_list, test_function)
## Warning in log(x): NaNs produced
## [[1]]
## [1] 1.609438
##
## [[2]]
## [1] NA
##
## [[3]]
## [1] NaN
##
## [[4]]
## [1] -Inf
##
## [[5]]
## [1] NA
- Step 6: Create a numeric vector with
log and test_function.
map_dbl(test_list, log)
# Error in .Primitive("log")(x, base) : non-numeric argument to mathematical function
map_dbl(test_list, test_function)
## Warning in log(x): NaNs produced
## [1] 1.609438 NA NaN -Inf NA