Easy error handling in R with purrr’s possibly

It’s discouraging to see your code choke section of the way by whilst attempting to utilize a operate in R. You may well know that one thing in 1 of those objects triggered a difficulty, but how do you monitor down the offender?

The purrr package’s perhaps() operate is 1 quick way.

In this case in point, I’ll demo code that imports multiple CSV data files. Most files’ benefit columns import as people, but 1 of these will come in as numbers. Working a operate that expects people as enter will result in an error.

For set up, the code under masses several libraries I have to have and then uses foundation R’s list.data files() operate to return a sorted vector with names of all the data files in my data listing. 

my_data_data files <- list.files("data_files", full.names = TRUE) %>%

I can then import the initial file and seem at its construction. 

x <- rio::import("data_files/file1.csv")
'data.frame':	3 obs. of  3 variables:
 $ Category     : chr  "A" "B" "C"
 $ Value        : chr  "$4,256.48 " "$438.22" "$945.12"
 $ MonthStarting: chr  "12/1/20" "12/1/20" "12/1/20"

Both the Value and Month columns are importing as character strings. What I in the end want is Value as numbers and MonthStarting as dates. 

Copyright © 2020 IDG Communications, Inc.