How can I make a list of lists in R?

后端 未结 5 674
逝去的感伤
逝去的感伤 2020-12-24 00:58

I don\'t know how to make a list of lists in R. I have several lists, I want to store them in one data structure to make accessing them easier. However, it looks like you ca

相关标签:
5条回答
  • 2020-12-24 01:30

    If you are trying to keep a list of lists (similar to python's list.append()) then this might work:

    a <- list(1,2,3)
    b <- list(4,5,6)
    c <- append(list(a), list(b))
    
    > c
    [[1]]
    [[1]][[1]]
    [1] 1
    
    [[1]][[2]]
    [1] 2
    
    [[1]][[3]]
    [1] 3
    
    
    [[2]]
    [[2]][[1]]
    [1] 4
    
    [[2]][[2]]
    [1] 5
    
    [[2]][[3]]
    [1] 6
    
    0 讨论(0)
  • 2020-12-24 01:30

    The example creates a list of named lists in a loop.

      MyList <- list()
      for (aName in c("name1", "name2")){
        MyList[[aName]] <- list(aName)
      }
      MyList[["name1"]]
      MyList[["name2"]]
    

    To add another list named "name3" do write:

      MyList$name3 <- list(1, 2, 3)
    
    0 讨论(0)
  • 2020-12-24 01:48

    Using your example::

    list1 <- list()
    list1[1] = 1
    list1[2] = 2
    list2 <- list()
    list2[1] = 'a'
    list2[2] = 'b'
    list_all <- list(list1, list2)
    

    Use '[[' to retrieve an element of a list:

    b = list_all[[1]]
     b
    [[1]]
    [1] 1
    
    [[2]]
    [1] 2
    
    class(b)
    [1] "list"
    
    0 讨论(0)
  • 2020-12-24 01:49

    You can easily make lists of lists

    list1 <- list(a = 2, b = 3)
    list2 <- list(c = "a", d = "b")
    mylist <- list(list1, list2)
    

    mylist is now a list that contains two lists. To access list1 you can use mylist[[1]]. If you want to be able to something like mylist$list1 then you need to do somethingl like

    mylist <- list(list1 = list1, list2 = list2)
    # Now you can do the following
    mylist$list1
    

    Edit: To reply to your edit. Just use double bracket indexing

    a <- list_all[[1]]
    a[[1]]
    #[1] 1
    a[[2]]
    #[1] 2
    
    0 讨论(0)
  • 2020-12-24 01:50

    As other answers pointed out in a more complicated way already, you did already create a list of lists! It's just the odd output of R that confuses (everybody?). Try this:

    > str(list_all)
    List of 2
     $ :List of 2
      ..$ : num 1
      ..$ : num 2
     $ :List of 2
      ..$ : chr "a"
      ..$ : chr "b"
    

    And the most simple construction would be this:

    > str(list(list(1, 2), list("a", "b")))
    List of 2
     $ :List of 2
      ..$ : num 1
      ..$ : num 2
     $ :List of 2
      ..$ : chr "a"
      ..$ : chr "b"
    
    0 讨论(0)
提交回复
热议问题