R - store a matrix into a single dataframe cell

后端 未结 2 1629
旧时难觅i
旧时难觅i 2020-12-15 13:13

I\'m trying to store an entire matrix/array into a single cell of a data frame, but can\'t quite remember how to do it.

Now before you say it can\'t be done

相关标签:
2条回答
  • 2020-12-15 13:41

    I think the trick may be to insert it in as a list:

    set.seed(123)
    dat <- data.frame(women, m=I(replicate(nrow(women), matrix(rnorm(4), 2, 2), 
                    simplify=FALSE)))
    
    
    str(dat)
    'data.frame':   15 obs. of  3 variables:
     $ height: num  58 59 60 61 62 63 64 65 66 67 ...
     $ weight: num  115 117 120 123 126 129 132 135 139 142 ...
     $ m     :List of 15
      ..$ : num [1:2, 1:2] -0.5605 -0.2302 1.5587 0.0705
      ..$ : num [1:2, 1:2] 0.129 1.715 0.461 -1.265
      ...
      ..$ : num [1:2, 1:2] -1.549 0.585 0.124 0.216
      ..- attr(*, "class")= chr "AsIs"
    
    dat[[1, "m"]]
               [,1]       [,2]
    [1,] -0.5604756 1.55870831
    [2,] -0.2301775 0.07050839
    
    dat[[2, "m"]]
              [,1]       [,2]
    [1,] 0.1292877  0.4609162
    [2,] 1.7150650 -1.2650612
    

    EDIT: So the question really is about initialising and then assigning. Given that, you should be able to define a data.frame like the one in your question like so:

    data.frame(i=1:5, m=I(vector(mode="list", length=5)))
    

    You can then assign to it like so:

    dat[[2, "m"]] <- matrix(rnorm(9), 3, 3)
    
    0 讨论(0)
  • 2020-12-15 14:08

    I think I worked it out. It is important to initialise the data frame such that the column is ready to accept matrices.

    To do this you give it a list data type. Note the I to protect the list().

    myDF <- data.frame(i=integer(), m=I(list()))
    

    Then you can add rows as usual

    myDF[1, 'i'] <- 1
    

    and then add the matrix in with [[]] notation

    myDF[[1, 'm']] <- matrix(rnorm(9), 3, 3)
    

    Access with [[]] notation:

    > myDF$m[[1]]
              [,1]       [,2]       [,3]
    [1,] 0.3307403 -0.2031316  1.5995385
    [2,] 0.4588922  0.1631086 -0.2754463
    [3,] 0.0568791  1.0358552 -0.1623794
    

    To initialise with non-zero rows you can do (note the I to protect the vector and the vector('list', 5) to initialise an empty list of length 5 to avoid wasting memory):

    myDF <- data.frame(i=1:5, m=I(vector('list', 5)))
    myDF$m[[1]] <- matrix(rnorm(9), 3, 3)
    
    0 讨论(0)
提交回复
热议问题