How to make a list of integer vectors in R

前端 未结 2 656
有刺的猬
有刺的猬 2021-02-02 07:56

Basic question: In R, how can I make a list and later populate it with vector elements?

l <- list() 
l[1] <- c(1,2,3) 

This gives the err

相关标签:
2条回答
  • 2021-02-02 08:08

    According to ?"[" (under the section "recursive (list-like) objects"):

     Indexing by ‘[’ is similar to atomic vectors and selects a list of
     the specified element(s).
    
     Both ‘[[’ and ‘$’ select a single element of the list.  The main
     difference is that ‘$’ does not allow computed indices, whereas
     ‘[[’ does.  ‘x$name’ is equivalent to ‘x[["name", exact =
     FALSE]]’.  Also, the partial matching behavior of ‘[[’ can be
     controlled using the ‘exact’ argument.
    

    Basically, for lists, [ selects more than one element, so the replacement must be a list (not a vector as in your example). Here's an example of how to use [ on lists:

    l <- list(c(1,2,3), c(4,5,6))
    l[1] <- list(1:2)
    l[1:2] <- list(1:3,4:5)
    

    If you only want to replace one element, use [[ instead.

    l[[1]] <- 1:3
    
    0 讨论(0)
  • 2021-02-02 08:15

    Use [[1]] as in

    l[[1]] <- c(1,2,3)
    l[[2]] <- 1:4
    

    and so. Also recall that preallocation is much more efficient, so if you know how long your list is going to be, use something like

    l <- vector(mode="list", length=N)
    
    0 讨论(0)
提交回复
热议问题