gpt4 book ai didi

r - 为什么 R 字符向量和数字向量在某些上下文中相等?

转载 作者:行者123 更新时间:2023-12-01 13:11:45 28 4
gpt4 key购买 nike

我注意到在 R数字的字符向量等价于它们对应的数字向量。

"1234" == 1234
# [1] TRUE
c("1", "2", "3") == 1:3
# [1] TRUE TRUE TRUE
all(c("1", "2", "3") == 1:3)
# [1] TRUE

使用时 all.equal()我们收到一条消息,即模式不同。
all.equal(c("1", "2"), c(1, 2))
# [1] "Modes: character, numeric" "target is character, current is numeric"

使用列表时,这会变得更加复杂。
myList <- list("1"="a", "2"=c("b", "c"))
myList[c("2", "1")]
# $`2`
# [1] "b" "c"
#
# $`1`
# [1] "a"

myList[2:1]
# $`2`
# [1] "b" "c"
#
# $`1`
# [1] "a"

myList[[2]]
# [1] "b" "c"

在这一点上,人们可能会推断在访问列表时数字向量和字符向量可以互换使用。但是之后...
myList2 <- list("1"="a", "23"=c("b", "c"))
myList2[c(23, 1)]
# $<NA>
# NULL
#
# $`1`
# [1] "a"

myList2[[23]]
# Error in myList2[[23]] : subscript out of bounds

myList2[["23"]]
# [1] "b" "c"

这种行为的解释是什么?

R 版本 3.5.0

最佳答案

阅读最近的帖子:Why does as.numeric(1) == (3 | 4) evaluate to TRUE?

特别是:

coercion rules for comparison operators ( ?Comparison ) 告诉我们:

If the two arguments are atomic vectors of different types, one is coerced to the type of the other, the (decreasing) order of precedence being character, complex, numeric, integer, logical and raw.



所以 1 == '1'真比较 as.character(1) == '1'这是 '1' == '1'这是 TRUE .

您尝试的其他操作与这些强制规则无关。

关于r - 为什么 R 字符向量和数字向量在某些上下文中相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50721720/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com