【发布时间】:2018-05-04 15:29:36
【问题描述】:
我正在掌握 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 似乎只返回错误?
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>
【问题讨论】:
-
map、map2和pmap类似于带有两个参数的lapply、mapply和带有任意数量参数的mapply。例如:map2(x.bad, y, safe_sum). -
mapply有SIMPLIFY = TRUE。您可以将其更改为SIMPLIFY = FALSE或使用Map -
留在
purrr宇宙中而不是将其与基本Rapply混合可能是一个好主意。无论如何,输出是我所期望的:结果总是 NA 并且信息性消息存储在error中,而且它被简化为矩阵。