R:“match”与列表的行为不一致

问题描述 投票:0回答:1

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
r match
1个回答
0
投票

原因是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)"
© www.soinside.com 2019 - 2024. All rights reserved.