Why does is.vector() return TRUE for list?

前端 未结 2 1289
一向
一向 2020-12-10 01:13

I\'m an R beginner. Browsing the R documentation, I stumbled upon this sentence ?is.vector: \"If mode = \"any\", is.vector may return TRUE for the atomic

相关标签:
2条回答
  • 2020-12-10 01:44

    See the R Internal Structures section (specifically section 1.1.1) of the R Internals manual. A list (in the sense you're speaking of) is a VECSXP, a type of vector.

    0 讨论(0)
  • 2020-12-10 01:52

    A list is (in most cases) itself a vector. From the help files for ?list: "Most lists in R internally are Generic Vectors, whereas traditional dotted pair lists (as in LISP) are available but rarely seen by users (except as formals of functions)."

    This means you can use vector to pre-allocate memory for a list:

    x <- vector("list", 3)
    class(x)
    [1] "list"
    

    Now allocate a value to the second element in the list:

    x[[2]] <- 1:5
    
    x
    
    [[1]]
    NULL
    
    [[2]]
    [1] 1 2 3 4 5
    
    [[3]]
    NULL
    

    See ?list and ?vector for more details.

    0 讨论(0)
提交回复
热议问题