I've noticed that in R
character vectors of numbers are equivalent to their corresponding numeric vectors.
"1234" == 1234
# [1] TRUE
c("1", "2", "3") == 1:3
# [1] TRUE TRUE TRUE
all(c("1", "2", "3") == 1:3)
# [1] TRUE
When using all.equal()
we get a message that the modes are different.
all.equal(c("1", "2"), c(1, 2))
# [1] "Modes: character, numeric" "target is character, current is numeric"
This gets even more complicated when using lists.
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"
At this point, one might infer that numeric and character vectors can be used interchangeably when accessing a list. But then...
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"
What is the explanation for this behavior?
R version 3.5.0