我有一个矩阵列表,我想能够cbind
到一个矩阵中,但是当它们有不同大小的行时遇到问题。为了解决这个问题,我试图将空行添加到较短行的底部,但是倒数第二步并不是很有效。
## LIST OF MATRACIES
lst = list(as.matrix(data.frame(1:3, 1:3)), as.matrix(data.frame(1:2, 1:2)))
## FIND LONGEST ONE
mrow = lapply(lst, function(x) nrow(x))
mrow = max(unlist(lst))
## CREATE MATRIX LIST TO RBIND
tempM = lapply(1:length(lst), function(x) matrix(nrow = mrow - nrow(lst[x][[1]]), ncol = ncol(lst[x][[1]])))
## ADD ROWS TO SHORTER MATRICES TO MAkE LENGTHS LINE UP
## THIS IS WHERE THINGS GO WRONG
lst = lapply(1:length(tempM), function(x) rbind(lst[x][[1]], tempM[x]))
## GOAL TO BE ABLE TO:
rlist::list.cbind(lst) ## ERROR: Different number of rows
答案 0 :(得分:1)
我从here中偷取了一个很棒的功能,它应该完全符合您的要求:
cbind.fill <- function(...){
nm <- list(...)
nm <- lapply(nm, as.matrix)
n <- max(sapply(nm, nrow))
do.call(cbind, lapply(nm, function (x)
rbind(x, matrix(, n-nrow(x), ncol(x)))))
}
您可以使用lst
do.call
lst&lt; - list(as.matrix(data.frame(1:3,1:3)),as.matrix(data.frame(1:2,1:2)))
do.call(cbind.fill,lst)
# X1. X1.3.1 X1.2 X1.2.1
# [1,] 1 1 1 1
# [2,] 2 2 2 2
# [3,] 3 3 NA NA
答案 1 :(得分:1)
另一种剥皮猫的方法:
library(tidyverse)
lst = list(as.matrix(data.frame(1:3, 1:3)),
as.matrix(data.frame(1:2, 1:2))
)
targheight <- reduce(lst,function(a,b){max(nrow(a),nrow(b))})
lst <- reduce(map(lst,function(x){rbind(x,matrix(nrow=targheight-dim(x)[1],ncol=dim(x)[2]))}),cbind)