我在列表index.1
中设置了30个名为index.30
到listname
的矩阵。我可以使用do.call
:
new.matrix = do.call(rbind, listname)
但是如何在矩阵中创建一个变量作为指示器来显示每个观察源自哪个矩阵?
答案 0 :(得分:2)
mat1<-matrix(c(1,1,0,0),byrow=TRUE,nrow=2)
mat2<-matrix(c(13,3,0,0),byrow=TRUE,nrow=2)
mat1
mat2
matindex<-c(rep(1,length(mat1[,1])),rep(2,length(mat2[,1])))
listname<-list(mat1,mat2)
new.matrix <- do.call(rbind, listname)
finalnewmatrix<-cbind(new.matrix,matindex)
finalnewmatrix
# or if you want the index as rownames then...
# rownames(new.matrix)<-matindex
要自动执行此操作并保存许多矩阵的输入,您可以这样做:
lengths <- sapply(listname, nrow)
matindex <- rep(seq_along(listname), lengths)
new.matrix <- do.call(rbind, listname)
finalnewmatrix <- cbind(new.matrix, matindex)