match
在使用列表对象时给出不一致的结果:
match(list(c(1, 2)), list(c(1L, 2L)))
#> [1] NA
match(list(c(1, 3)), list(c(1L, 3L)))
#> [1] 1
match
中到底发生了什么导致了这种情况?
这不仅仅是
integer
和numeric
之间的区别:
match(c(1, 2), c(1L, 2L))
#> [1] 1 2
match(c(1, 3), c(1L, 3L))
#> [1] 1 2
一些额外的例子。该行为似乎仅在连续值时才会出现:
match(list(c(100, 101, 102)), list(c(100L, 101L, 102L)))
#> [1] NA
match(list(c(100, 102, 101)), list(c(100L, 102L, 101L)))
#> [1] 1
match(list(c(2, 1)), list(c(2L, 1L)))
#> [1] NA
原因是1,2是连续数字。
在
?match
的详细部分,提到:
将因子、原始向量和列表转换为字符向量,然后将 x 和 table 强制转换为通用类型(R 排序中两种类型中的后者,逻辑 < integer < numeric < complex < character) before matching. If incomparables has positive length it is coerced to the common type.
对于连续整数,它们被解析为
starting number: ending number
as.character(list(c(1L,2L)))
[1] "1:2"
as.character(list(c(100L, 101L, 102L)))
[1] "100:102"
与其他:
as.character(list(c(1L,3L)))
[1] "c(1, 3)"
as.character(list(c(1,2)))
[1] "c(1, 2)"