Why this behavior when coercing a list to character via as.character()?

前端 未结 2 1228
时光取名叫无心
时光取名叫无心 2020-12-01 17:23

In the process of (mostly) answering this question, I stumbled across something that I feel like I really should already have seen before. Let\'s say you\'ve got a list:

相关标签:
2条回答
  • 2020-12-01 17:34

    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.

    0 讨论(0)
  • 2020-12-01 17:45

    For non-trivial lists, as.character uses deparse to generate the strings.

    1. Only if the vector is integer and 1,2,3,...,n - then it deparses as 1:n.

      c(1,2,3) is double whereas 1:3 is integer...

    2. 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)
    
    0 讨论(0)
提交回复
热议问题