如何处理 "pmap" 错误和包装在 "safely" 中的函数的结果输出。不能解除嵌套
How to handle "pmap" error and result output from function wrapped in "safely". Can't unnest
我经常使用 PURRR 的 pmap 函数对输入的行应用函数 table 并内联检索它们。最近我开始使用围绕我在 pmap 函数中应用的函数的“安全”函数。这很好用,但我很难弄清楚当输出列中同时存在错误和结果时如何处理它的输出。
我想内联提取错误“消息”对象,但是由于 NA 和错误的混合,这似乎不可能?有人知道怎么做吗?
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()
使用map
和pluck
-
library(tidyverse)
result %>%
unnest_wider(col = function_output) %>%
mutate(error_message = map(error, pluck, 'message'))
或-
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.
我经常使用 PURRR 的 pmap 函数对输入的行应用函数 table 并内联检索它们。最近我开始使用围绕我在 pmap 函数中应用的函数的“安全”函数。这很好用,但我很难弄清楚当输出列中同时存在错误和结果时如何处理它的输出。
我想内联提取错误“消息”对象,但是由于 NA 和错误的混合,这似乎不可能?有人知道怎么做吗?
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()
使用map
和pluck
-
library(tidyverse)
result %>%
unnest_wider(col = function_output) %>%
mutate(error_message = map(error, pluck, 'message'))
或-
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.