Easy error handling in R with purrr’s possibly

It’s discouraging to see your code choke section of the way by way of though making an attempt to use a operate in R. You may know that anything in a person of these objects triggered a challenge, but how do you observe down the offender?

The purrr package’s potentially() operate is a person uncomplicated way.

In this case in point, I’ll demo code that imports many CSV data files. Most files’ price columns import as people, but a person of these comes in as figures. Jogging a operate that expects people as enter will induce an mistake.

For setup, the code underneath masses a number of libraries I need to have and then utilizes base R’s list.data files() operate to return a sorted vector with names of all the data files in my information listing. 

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

I can then import the to start with file and search 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 of those the Worth and Month columns are importing as character strings. What I in the long run want is Worth as figures and MonthStarting as dates. 

Copyright © 2020 IDG Communications, Inc.

Maria J. Danford

Next Post

Predictions for cloud computing in 2021

Thu Dec 17 , 2020
Cloud computing is the centerpiece of the world’s technical response to the COVID-19 crisis. Indeed, the leading general public cloud providers have been standout company successes in this most strange of decades. As corporations just about everywhere managed to retain the lights on by possessing staff do the job from […]

You May Like