purrr::map_int
関数が単純な足し算で失敗したとき、数値リテラルの型が原因かもしれません。
次のコードで(1)はエラー、(2)は成功します。違いは足す数が1
か1L
かです。
require(purrr) 1:10 %>% map_int(~.x+1) #> Error: Can't coerce element 1 from a double to a integer 1:10 %>% map_int(~.x+1L) #> [1] 2 3 4 5 6 7 8 9 10 11
原因はRの数値リテラルがサフィックスなしでdouble
型であることです。これは次のコードで確かめられます。
typeof(1) # [1] "double" typeof(1L) # [1] "integer"
purrr::map_int
関数は戻り値をinteger
型に制限しているので、~.+1
の結果がdouble
型となることからエラーとなります。解決策は上記コードのように1L
とサフィックスで型指定するか、purrr::map_dbl
関数を使うことです。
参考: - https://stackoverflow.com/questions/55397509/purrrmap-int-cant-coerce-element-1-from-a-double-to-a-integer - 3.1.1 Constants - R Language Definition - purrr::map - tidyverse