Charlie_Dont_Surf
Charlie_Dont_Surf

Reputation: 41

Issue running purrr::possible for error recovery inside ~ tibble

I was working through an example from the Hadley Wickham's "The Joy of Functional Programming (for Data Science)" (available on youtube) lecture on purrr and wanted to add in error-recovery using possibly() to handle any zip files that fail to be read.

A bit of his code;

paths <- dir_ls("NSFopen_Alldata/", glob= ".zip")

files<- map_dfr(paths, ~ tibble(path=.x, files= unzip(.x, list = TRUE)$Name))

Adding error recovery with possibly();

unzip_safe <- possibly(.f= unzip, otherwise = NA)

files<- map_dfr(paths, ~ tibble(path=.x, files= unzip_safe(.x, list = TRUE)$Name))

I get the following error: $ operator is invalid for atomic vectors.

Is this because possibly is in a tibble?

Upvotes: 0

Views: 47

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389315

Files that fail return an NA and you are trying to extract $Name from it which returns an error. See

NA$NAme

Error in NA$NAme : $ operator is invalid for atomic vectors

Extract $Name from the successful files in possibly itself. Try :

library(purrr)
unzip_safe <- possibly(.f= ~unzip(., list = TRUE)$Name, otherwise = NA)
files <- map_dfr(paths, ~ tibble(path=.x, files = unzip_safe(.x))

Upvotes: 1

Related Questions