Why this behavior when coercing a list to character via as.character()?
For non-trivial lists, as.character
uses deparse
to generate the strings.
-
Only if the vector is integer and 1,2,3,...,n - then it deparses as
1:n
.c(1,2,3)
is double whereas1:3
is integer... No idea :-)
...but look at deparse
if you want to understand as.character
here:
deparse(c(1L, 2L, 3L)) # 1:3
deparse(c(3L, 2L, 1L)) # c(3L, 2L, 1L)
deparse(c(1, 2, 3)) # c(1, 2, 3)
The help file does say
For lists it deparses the elements individually, except that it extracts the first element of length-one character vectors.
I'd seen this before in trying to answer a question [not online] about grep
. Consider:
> x <- list(letters[1:10],letters[10:19])
> grep("c",x)
[1] 1 2
grep
uses as.character
on x
, with the result that, since both have c(
in them, both components match. That took a while to figure out.
On "Why does it do this?", I'd guess that one of the members of R core wanted it to do this.