purrr's possibly

I have two functions here to just do some clean up of csv files,

function A and function B.

The logic I have is whatever .csv that function B encounters, if the dataframe doesn't have column Sales_UPDT, it should encounter an error so it should trigger , function A, but it doesn't seem to work...

It would just stop, but nothing gets triggered.

A = function(X) {
  vroom(X)%>% 
    mutate(Sales_DT= substr(Sales, 1, 10),) %>% 
    write.csv(paste0(X, ".csv"), row.names = FALSE) }


B= function(X) {
  vroom(X)%>% 
    mutate(Sales_DT= substr(Sales, 1, 10), Sales_UPDT= substr(Sales, 1, 10)) %>% 
    write.csv(paste0(X, ".csv"), row.names = FALSE) }

map(File, 
    possibly(B, otherwise = 
           possibly(A, otherwise = "error")
 )

any help is great!

I think the file business is potentially distracting so I might some simpler functions that process numbers/throw errors.

A = function(x) {
    stopifnot(x>0)
   x^2
   }
B= function(x) {
 stopifnot(x>100)
  log(x)
  }

If I had to nest possibly's in the way you outline I would probably prefer to make them into their own function explicitly like so:

C= function(x) {
possibly(B, otherwise = possibly(A, otherwise = "error")(x))(x)
}

map(c(200,4,0), 
    C
)

doing an inline version would look like this instead:


map(c(200,4,0), 
    ~possibly(B, otherwise = possibly(A, otherwise = "error")(.x))(.x)
)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.