简体   繁体   English

如何重新排列矩阵列表中的每个矩阵?

[英]How do I rbind every number of matrices in a list of matrices?

Let's say I have this list of matrices: 假设我有以下矩阵列表:

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

I want to merge c1+c2, c3+c4, c5+c6 and keep them in a list. 我想合并c1+c2, c3+c4, c5+c6并将它们保留在列表中。 I could this manually with the following code: 我可以使用以下代码手动进行操作:

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)

But because my actual data will be much larger, this method would be very time consuming. 但是因为我的实际数据会更大,所以这种方法将非常耗时。 Is there a much quicker way to do it? 有更快的方法吗?

尝试这个:

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

How about the following? 接下来呢?

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

We create a grouping variable g (equal to c(1, 1, 2, 2, ...) ) and then split by it and rbind the elements of each component together: 我们创建一个分组变量g (等于c(1, 1, 2, 2, ...) rbind c(1, 1, 2, 2, ...) ),然后将其除以将每个组件的元素rbind在一起:

n <- length(clist)
g <- c(gl(n, 2, n))
lapply(split(clist, g), "do.call", what = "rbind")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM