I often use PURRR's pmap function to apply a function on rows of an input table and retrieve them inline. Recently I've started using the "safely" function wrapped around the function I'm applying within the pmap function. This works great but I'm having a hard time figuring out how to handle it's output when both errors and results are available within the output column.
I want to extract the error "message" object inline however this does not seem possible due to the mix of NAs and errors? Does anyone know how to do this?
library(tidyverse)
library(openxlsx)
example_data <- tribble(~input_col,
r"(C:\Users\Documents\example data.xlsx)",
r"(C:\does not exist.xlsx)")
result <- example_data %>%
mutate(function_output = pmap(list(xlsxFile = input_col), safely(read.xlsx)))
#returns result and error columns
result %>%
unnest_wider(col = function_output, names_sep='_') %>%
View()
#does not return the error message?
result %>%
unnest_wider(col = function_output) %>%
mutate(error_message=error$message) %>%
View()
# This seems to extract all the items from the list object but does not preserve table structure
result %>% unnest_wider(col = function_output) %>%
mutate(across(where(is.list) & starts_with("error"), flatten)) %>%
View()
CodePudding user response:
Use map
and pluck
-
library(tidyverse)
result %>%
unnest_wider(col = function_output) %>%
mutate(error_message = map(error, pluck, 'message'))
Or -
result %>%
unnest_wider(col = function_output) %>%
mutate(error_message = map_chr(error,
~if(is.null(.x)) NA_character_ else .x$message))
# input_col result error error_message
# <chr> <list> <list> <chr>
#1 result.xlsx <df [3 × 12]> <NULL> NA
#2 does not exist.xlsx <NULL> <smplErrr> File does not exist.