为什么函数在使用 purrr::possibly 时不能正确映射到值?
Why is function not properly mapping to values while using purrr::possibly?
我正在尝试使用 purrr::possibly()
来跳过我代码中的错误,但出于某种原因,当我在这里使用 possibly()
时,它 returns 输出就好像一切是一个错误。
这是一个例子:
library(purrr)
add_things <- function(number) {
new_number <- number + 1
return(new_number)
}
possibly_add_things <- possibly(add_things, otherwise = NA)
# Works
map(c(1, 2, 3), possibly_add_things)
#> [[1]]
#> [1] 2
#>
#> [[2]]
#> [1] 3
#>
#> [[3]]
#> [1] 4
# Shouldn't be all NAs -- only the 2nd one
map(c(1, "hi", 3), possibly_add_things)
#> [[1]]
#> [1] NA
#>
#> [[2]]
#> [1] NA
#>
#> [[3]]
#> [1] NA
由 reprex package (v1.0.0)
创建于 2021-05-11
如有任何建议,我们将不胜感激。
问题是 vector
是由其单一类型和大小或长度定义的。当我们使用 c
时,它连接到一个 vector
并且根据类型的优先级, character
具有更高的优先级,因此所有元素都转换为 character
。相反,输入应该是 list
map(list(1, 'hi', 3), possibly_add_things)
#[[1]]
#[1] 2
#[[2]]
#[1] NA
#[[3]]
#[1] 4
我正在尝试使用 purrr::possibly()
来跳过我代码中的错误,但出于某种原因,当我在这里使用 possibly()
时,它 returns 输出就好像一切是一个错误。
这是一个例子:
library(purrr)
add_things <- function(number) {
new_number <- number + 1
return(new_number)
}
possibly_add_things <- possibly(add_things, otherwise = NA)
# Works
map(c(1, 2, 3), possibly_add_things)
#> [[1]]
#> [1] 2
#>
#> [[2]]
#> [1] 3
#>
#> [[3]]
#> [1] 4
# Shouldn't be all NAs -- only the 2nd one
map(c(1, "hi", 3), possibly_add_things)
#> [[1]]
#> [1] NA
#>
#> [[2]]
#> [1] NA
#>
#> [[3]]
#> [1] NA
由 reprex package (v1.0.0)
创建于 2021-05-11如有任何建议,我们将不胜感激。
问题是 vector
是由其单一类型和大小或长度定义的。当我们使用 c
时,它连接到一个 vector
并且根据类型的优先级, character
具有更高的优先级,因此所有元素都转换为 character
。相反,输入应该是 list
map(list(1, 'hi', 3), possibly_add_things)
#[[1]]
#[1] 2
#[[2]]
#[1] NA
#[[3]]
#[1] 4