How to create a matrix of lists in R?

前端 未结 1 738
误落风尘
误落风尘 2020-12-11 05:04

What i want to have is a matrix in which each element is a list itself. See the following example:



        
相关标签:
1条回答
  • 2020-12-11 05:25

    This builds that matrix although the print method does not display it in the manner you imagined:

     matrix( list(c(1,2,4), c(NULL), c(1,2), c(3,4,5,6), c(1), c(1,3)), 2,3)
     #---------
         [,1]      [,2]      [,3]     
    [1,] Numeric,3 Numeric,2 1        
    [2,] NULL      Numeric,4 Numeric,2
    

    Inspect the first element:

    > Mlist <- matrix( list(c(1,2,4), c(NULL), c(1,2), c(3,4,5,6), c(1), c(1,3)), 2,3)
    > Mlist[1,1]
    [[1]]
    [1] 1 2 4
    
    > is.matrix(Mlist)
    [1] TRUE
    > class( Mlist[1,1] )
    [1] "list"
    

    Demonstration of creating "matrix of lists" from a list:

    > will.become.a.matrix <- list(c(1,2,4), c(NULL), c(1,2), c(3,4,5,6), c(1), c(1,3))
    > is.matrix(will.become.a.matrix)
    [1] FALSE
    > dim(will.become.a.matrix) <- c(2,3)
    > is.matrix(will.become.a.matrix)
    [1] TRUE
    > dim(will.become.a.matrix)
    [1] 2 3
    > class(will.become.a.matrix[1,1])
    [1] "list"
    

    Further requested demonstration:

     A<- list(); F=list() E=list()
     A[1]<-c(3) ;  F[[1]]<-numeric(0);  E[[1]]<-numeric(0)
     A[2]<-c(1) ;  F[2]<-c(1)   ;        E[2]<-c(1)
     A[3]<-c(1) ;  F[3]<-c(2)  ;         E[[3]]<-numeric(0)
     A[[4]]<-list(1,3) ;F[[4]]<-numeric(0) ; E[[4]]<-numeric(0)
     A[5]<-c(4) ; F[5]<-c(4)       ;    E[5]<-c(4)
     Mlist= c(A,F,E)
     M <- matrix(Mlist, length(A), 3)
    #=====================================
    > M
         [,1]   [,2]      [,3]     
    [1,] 3      Numeric,0 Numeric,0
    [2,] 1      1         1        
    [3,] 1      2         Numeric,0
    [4,] List,2 Numeric,0 Numeric,0
    [5,] 4      4         4        
    

    You asked (in comments) "....is there a way to define number of column and rows , but not the element itself because they are unknown?"

    Answered (initially in comments)

    b<-matrix(rep(list(), 6),nrow = 2, ncol =3) 
    #.... then replace the NULL items with values. 
    # Need to use "[[": for assignment (which your 'Update 1' did not 
    # ....and your Update2 only did for some but not all of the assignments.)
    
    b[[1]] <- c(1,2,3,4) 
    
    0 讨论(0)
提交回复
热议问题