我怀疑这是 purrr 包中的错误,但想先在 StackOverflow 中检查我的逻辑。
在我看来,possibly
功能在内部不起作用map2_chr
功能。我正在使用 purrr 版本 0.2.5
考虑这个例子:
library(dplyr)
library(purrr)
lets <- tibble(posn = 2:0,
lets_list = list(letters[1:5], letters[1:5], letters[1:5])) %>%
glimpse()
回报
Observations: 3
Variables: 2
$ posn <int> 2, 1, 0
$ lets_list <list> [<"a", "b", "c", "d", "e">, <"a", "b", "c", "d", "e">, <"a", "b", "c", "d", "e">]
在此示例中,我想使用 mutate 创建另一列,以根据“posn”中的值返回列表“lets_list”中的元素。
lets %>%
mutate(lets_sel = map2_chr(lets_list, posn, ~.x[.y]))
失败并显示此错误消息,因为第三行的 posn = 0。
> lets %>%
+ mutate(lets_sel = map2_chr(lets_list, posn, ~.x[.y]))
# Error in mutate_impl(.data, dots) :
# Evaluation error: Result 3 is not a length 1 atomic vector.
使用possibly
功能与map2_chr
也返回错误。
lets %>%
mutate(lets_sel = map2_chr(lets_list, posn, possibly(~.x[.y], NA_character_)))
# Error in mutate_impl(.data, dots) :
# Evaluation error: Result 3 is not a length 1 atomic vector.
但是,那map2
功能工作正常:
> lets %>%
+ mutate(lets_sel = map2(lets_list, posn, possibly(~.x[.y], NA_character_)))
# A tibble: 3 x 3
posn lets_list lets_sel
<int> <list> <list>
1 2 <chr [5]> <chr [1]>
2 1 <chr [5]> <chr [1]>
3 0 <chr [5]> <chr [0]>
解决方法是先使用map2,然后使用map_chr,但我怀疑这是一个错误。
> lets %>%
+ mutate(lets_sel = map2(lets_list, posn, ~.x[.y]),
+ lets_sel = map_chr(lets_sel, possibly(~.x[1], NA_character_)))
# A tibble: 3 x 3
posn lets_list lets_sel
<int> <list> <chr>
1 2 <chr [5]> b
2 1 <chr [5]> a
3 0 <chr [5]> NA
我在这里错过了什么吗?
谢谢。