如何将各种尺寸的矩阵列表转换为参差不齐的数组?
这是一个矩阵列表(在我的实际用例中,它们都是由可变数量的行组成的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
simplify2array
和abind
等显而易见的方法似乎只在矩阵具有相同的维度时起作用,所以我有点卡住了。
答案 0 :(得分:3)
R没有乱七八糟的数组类。您需要保持列表格式并解决困难,或接受“额外行”中的NA值。
答案 1 :(得分: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