使用 purrr 捕捉 mapply 的错误

using purrr to catch errors with mapply

我正在掌握包 purrr 以及如何使用它来捕获代码问题。我似乎不理解与 mapply 一起使用时的输出。下面我概述了一个工作示例,这是实现代码的正确方法吗?

x.good <- c(2, 2, 3, 3)
x.bad <- c(2, 2, "A", 3)
y <- c(2, 2, 3, 3)
mapply(sum, x.good, y) # works just fine
mapply(sum, x.bad, y)  # understandably makes R unhappy

# Define a new function
library(purrr)
safe_sum <- safely(sum, otherwise=NA_real_)

# apply it
res <- mapply(safe_sum, x.bad, y)

res
       2      2      A      3     
result NA     NA     NA     NA    
error  List,2 List,2 List,2 List,2

教程中也使用了map函数,这里也需要这个吗?

更新

运行 map2 好像只有 return 个错误?

map2(x.bad, y, safe_sum)
[[1]]
[[1]]$result
[1] NA

[[1]]$error
<simpleError in sum(..., na.rm = na.rm): invalid 'type' (character) of     argument>


[[2]]
[[2]]$result
[1] NA

[[2]]$error
<simpleError in sum(..., na.rm = na.rm): invalid 'type' (character) of argument>


[[3]]
[[3]]$result
[1] NA

[[3]]$error
<simpleError in sum(..., na.rm = na.rm): invalid 'type' (character) of argument>


[[4]]
[[4]]$result
[1] NA

[[4]]$error
<simpleError in sum(..., na.rm = na.rm): invalid 'type' (character) of argument>

您的 x.bad 是一个字符向量。这就是这个例子中的问题。如果您将 x.bad 更改为安全示例中的列表,它将起作用,因为只有 "A" 将被定义为字符,其余的将是数字。

x.bad <- list(2, 2, "A", 3)
y <- c(2, 2, 3, 3)

library(purrr)

safe_sum <- safely(sum, otherwise=NA_real_)
map2(x.bad, y, safe_sum)
[[1]]
[[1]]$result
[1] 4

[[1]]$error
NULL


[[2]]
[[2]]$result
[1] 4

[[2]]$error
NULL


[[3]]
[[3]]$result
[1] NA

[[3]]$error
<simpleError in sum(..., na.rm = na.rm): invalid 'type' (character) of argument>


[[4]]
[[4]]$result
[1] 6

[[4]]$error
NULL

今天出现了一篇博客,其中通过示例进行了更详细的介绍。你可以找到它here