←
PDF 357 / 520 #> ..\$ : NULL #> ..\$ :List of 2 #> .. ..\$ message: chr "non-numeric argument to ..." #> .. ..
→
English · PDF 357
Original PDF page 357
中文 · PDF 357

#> ..$ : NULL #> ..$ :2 个元素的列表 #> .. ..$ message: 字符 "non-numeric argument to ..." #> .. ..$ call : 语言 .f(...) #> .. ..- attr(*, "class")=字符 [1:3] "simpleError" "error" ...

如何处理这些错误由你决定,但通常你要么查看 y 为错误的那些 x 的值,要么使用那些正常的 y 的值:

is_ok <- y$error %>% map_lgl(is_null) x[!is_ok] #> [[1]] #> [1] "a" y$result[is_ok] %>% flatten_dbl() #> [1] 0.0 2.3

purrr 还提供了另外两个有用的副词:

  • 与 safely() 一样,possibly() 也总是能成功执行。它比 safely() 更简单,因为你需要给它一个默认值,当出现错误时返回该值:

x <- list(1, 10, "a") x %>% map_dbl(possibly(log, NA_real_)) #> [1] 0.0 2.3 NA

  • quietly() 的作用与 safely() 类似,但它捕获的不是错误,而是打印输出、消息和警告:

x <- list(1, -1) x %>% map(quietly(log)) %>% str() #> 2 个元素的列表 #> $ :4 个元素的列表 #> ..$ result : 数值 0 #> ..$ output : 字符 "" #> ..$ warnings: 字符(0) #> ..$ messages: 字符(0) #> $ :4 个元素的列表 #> ..$ result : 数值 NaN #> ..$ output : 字符 "" #> ..$ warnings: 字符 "NaNs produced" #> ..$ messages: 字符(0)