如何在矩阵列表中对每个矩阵进行处理?

时间:2017-11-12 12:02:18

标签: r list matrix

假设我有这个矩阵列表:

c1 <- matrix(rnorm(10),5,2)
c2 <- c1+(rnorm(10))
c3 <- c1+(rnorm(10))
c4 <- c1+(rnorm(10))
c5 <- c1+(rnorm(10))
c6 <- c1+(rnorm(10))
clist <- list(c1,c2,c3,c4,c5,c6)

[[1]]
           [,1]        [,2]
[1,] -0.1591251  0.36887661
[2,]  0.4200732 -1.21884880
[3,] -0.6763903 -0.02593779
[4,]  0.1658612 -0.65441390
[5,] -1.4652644 -0.10981210

[[2]]
           [,1]        [,2]
[1,] -1.5475582  1.33232706
[2,]  0.9781123 -0.70260202
[3,] -1.1577471  2.04805617
[4,]  0.4535016 -1.08563438
[5,] -3.0072380  0.06337565

[[3]]
           [,1]       [,2]
[1,]  0.5475332 -0.7793278
[2,] -1.8806731 -1.1158255
[3,] -0.4837955 -0.8165737
[4,] -1.4951387 -0.2655842
[5,] -0.1487497 -0.4243752

[[4]]
             [,1]       [,2]
[1,] -1.270525331  0.5796936
[2,]  1.309900315 -2.4646281
[3,] -2.313890536  1.5281795
[4,]  0.003287924 -2.3560008
[5,] -1.903412482 -2.6763855

[[5]]
           [,1]        [,2]
[1,] -0.4553650  0.06665067
[2,] -0.4382334 -0.91694728
[3,] -1.8101902  0.29204456
[4,]  0.6602221 -0.45068171
[5,] -1.3796827  0.51264234

[[6]]
           [,1]       [,2]
[1,] -1.0130324  1.4233890
[2,]  0.9672156 -0.9425755
[3,] -2.5090911 -0.5489537
[4,]  0.7705731  1.0351301
[5,] -0.0414573 -1.8325651

我想合并c1+c2, c3+c4, c5+c6并将它们保存在列表中。我可以使用以下代码手动执行此操作:

cm1 <- do.call("rbind", clist[1:2])
cm2 <- do.call("rbind", clist[3:4])
cm3 <- do.call("rbind", clist[5:6])
cmlist <- list(cm1, cm2, cm3)

但是因为我的实际数据会大得多,所以这种方法非常耗时。有更快的方法吗?

3 个答案:

答案 0 :(得分:1)

试试这个:

cmlist1=lapply(seq(1,length(clist),by=2),function(x)do.call("rbind", clist[x:(x+1)]))

答案 1 :(得分:1)

以下情况如何?

mapply(rbind,
       clist[which(seq(1,length(clist)) %% 2 == 1)],
       clist[which(seq(1,length(clist)) %% 2 == 0)],
       SIMPLIFY = F)

答案 2 :(得分:1)

我们创建了一个分组变量sudo apt-get install libpq-dev (等于g),然后将其拆分并c(1, 1, 2, 2, ...)将每个组件的元素组合在一起:

rbind