2

如何将各种维度的矩阵列表转换为参差不齐的数组?

这是一个矩阵列表(在我的实际用例中,它们都是 2 列,行数可变):

set.seed(007)
my_list<- lapply(1:10, function(i) matrix(data = runif(sample(seq(2,10,2), 1)), ncol = 2))

看起来像这样:

my_list
[[1]]
           [,1]      [,2]
[1,] 0.39774545 0.3400624
[2,] 0.11569778 0.9720625
[3,] 0.06974868 0.1658555
[4,] 0.24374939 0.4591037
[5,] 0.79201043 0.1717481

[[2]]
           [,1]       [,2]
[1,] 0.77281195 0.45344777
[2,] 0.09630154 0.08470071

[[3]]
          [,1]      [,2]
[1,] 0.0087046 0.6394489
[2,] 0.9857371 0.2952232
[3,] 0.3165848 0.9967037

[[4]]
           [,1]      [,2]
[1,] 0.98873914 0.3622208
[2,] 0.06564574 0.6799935
[3,] 0.62703876 0.2637199
[4,] 0.49047504 0.1857143
[5,] 0.97102441 0.1851432

[[5]]
          [,1]      [,2]
[1,] 0.8470244 0.7905856
[2,] 0.4980761 0.8384639

[[6]]
          [,1]      [,2]
[1,] 0.7994758 0.4367756
[2,] 0.3819431 0.9042177
[3,] 0.7597012 0.3195349

[[7]]
          [,1]      [,2]
[1,] 0.8162891 0.8984762

[[8]]
          [,1]      [,2]
[1,] 0.5730689 0.3868313
[2,] 0.7200795 0.1627908
[3,] 0.7740586 0.1872283
[4,] 0.6277608 0.3912495
[5,] 0.7229893 0.2739012

[[9]]
          [,1]      [,2]
[1,] 0.5043918 0.7638404

[[10]]
          [,1]      [,2]
[1,] 0.5440542 0.3370636
[2,] 0.6590872 0.4245263
[3,] 0.4687284 0.2870151
[4,] 0.4818055 0.6011915

我想让它看起来像:

my_array
, , 1
           [,1]      [,2]
[1,] 0.39774545 0.3400624
[2,] 0.11569778 0.9720625
[3,] 0.06974868 0.1658555
[4,] 0.24374939 0.4591037
[5,] 0.79201043 0.1717481

, , 2
           [,1]       [,2]
[1,] 0.77281195 0.45344777
[2,] 0.09630154 0.08470071

, , 3
          [,1]      [,2]
[1,] 0.0087046 0.6394489
[2,] 0.9857371 0.2952232
[3,] 0.3165848 0.9967037

, , 4
           [,1]      [,2]
[1,] 0.98873914 0.3622208
[2,] 0.06564574 0.6799935
[3,] 0.62703876 0.2637199
[4,] 0.49047504 0.1857143
[5,] 0.97102441 0.1851432

, , 5
          [,1]      [,2]
[1,] 0.8470244 0.7905856
[2,] 0.4980761 0.8384639

, , 6
          [,1]      [,2]
[1,] 0.7994758 0.4367756
[2,] 0.3819431 0.9042177
[3,] 0.7597012 0.3195349

, , 7
          [,1]      [,2]
[1,] 0.8162891 0.8984762

, , 8
          [,1]      [,2]
[1,] 0.5730689 0.3868313
[2,] 0.7200795 0.1627908
[3,] 0.7740586 0.1872283
[4,] 0.6277608 0.3912495
[5,] 0.7229893 0.2739012

, , 9
          [,1]      [,2]
[1,] 0.5043918 0.7638404

, , 10
          [,1]      [,2]
[1,] 0.5440542 0.3370636
[2,] 0.6590872 0.4245263
[3,] 0.4687284 0.2870151
[4,] 0.4818055 0.6011915

诸如simplify2arrayand之类的显而易见的方法abind似乎只在矩阵都具有相同尺寸时才有效,所以我有点卡住了。

4

2 回答 2

3

R 没有参差不齐的数组类。您将需要保持列表格式并解决困难,或接受在“额外行”中包含 NA 值。

于 2013-08-18T04:32:01.287 回答
0

这行得通吗?

n<-do.call(rbind,my_list<- lapply(1:10, function(i) matrix(data = runif(sample(seq(2,10,2), 1)), ncol = 2)))
myrow<-list(4,3,1,5,2,3,4,2)
mycol<-list(2,2,2,3,2,2,2,2)
myz<-as.list(rep(1,8))


my_array<-Map(function(x,y,z) array(n,c(x,y,z)), myrow, mycol,myz) # but this creates the list of 1 array 
于 2013-08-17T17:59:50.217 回答