Easy error handling in R with purrr’s possibly

It’s frustrating to see your code choke part of the way through while trying to apply a function in R. You may know that something in one of those objects caused a problem, but how do you track down the offender?

The purrr package’s possibly() function is one easy way.

In this example, I’ll demo code that imports multiple CSV files. Most files’ value columns import as characters, but one of these comes in as numbers. Running a function that expects characters as input will cause an error.

For setup, the code below loads several libraries I need and then uses base R’s list.files() function to return a sorted vector with names of all the files in my data directory. 

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

I can then import the first file and look at its structure. 

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 ultimately want is Value as numbers and MonthStarting as dates. 

Copyright © 2020 IDG Communications, Inc.

Source link