purrr::map_int:无法将元素 1 从双精度强制转换为整数 [英] purrr::map_int: Can't coerce element 1 from a double to a integer
问题描述
我遇到了 purrr
包中的 map_int
最奇怪的错误.
I am having the weirdest bug with map_int
from the purrr
package.
# Works as expected
purrr::map_int(1:10, function(x) x)
#> [1] 1 2 3 4 5 6 7 8 9 10
# Why on earth is that not working?
purrr::map_int(1:10, function(x) 2*x)
#> Error: Can't coerce element 1 from a double to a integer
# or that?
purrr::map_int(1:10, round)
#> Error: Can't coerce element 1 from a double to a integer
由 reprex 包 (v0.2.1) 于 2019 年 3 月 28 日创建上>
Created on 2019-03-28 by the reprex package (v0.2.1)
我在 Rocker 容器 (Debian) 中运行 3.5.2,并使用最新的 github 版本:
I run 3.5.2 in rocker container (Debian) with the latest github version of everything:
sessioninfo::package_info("purrr")
#> package * version date lib source
#> magrittr 1.5.0.9000 2019-03-28 [1] Github (tidyverse/magrittr@4104d6b)
#> purrr 0.3.2.9000 2019-03-28 [1] Github (tidyverse/purrr@25d84f7)
#> rlang 0.3.2.9000 2019-03-28 [1] Github (r-lib/rlang@9376215)
#>
#> [1] /usr/local/lib/R/site-library
#> [2] /usr/local/lib/R/library
推荐答案
help(map)
的文档说
.f 的输出将自动向上输入,例如逻辑 ->整数 -> 双精度 -> 字符
The output of .f will be automatically typed upwards , e.g. logical -> integer -> double -> character
它似乎遵循了 help(c)
中给出的更大的顺序.例如,这会产生错误 map_dbl(1:10, ~complex(real = .x, imaginary = 1))
.
It appears to be following the larger ordering given in help(c)
. For example, this produces an error map_dbl(1:10, ~complex(real = .x, imaginary = 1))
.
NULL <原始的逻辑 <整数<双<复杂的<字符 <列表<表达
NULL < raw < logical < integer < double < complex < character < list < expression
正如您在该排序中所看到的,双精度到整数是向下转换.因此,该函数旨在不进行这种转换.
As you can see in that ordering, double-to-integer is a downward conversion. So, the function is designed to not do this kind of conversion.
解决方案是编写一个函数 .f
输出整数(或更低)分类的对象(如@Stéphane Laurent 的回答),或者只使用 as.integer(map(.x, .f))
.
The solution is to either write a function .f
which outputs integer (or lower) classed objects (as in @Stéphane Laurent's answer), or just use as.integer(map(.x, .f))
.
这是一种类型检查,这是一个有用的功能用于防止编程错误.
This is a kind of type-checking, which can be a useful feature for preventing programming mistakes.
这篇关于purrr::map_int:无法将元素 1 从双精度强制转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!