1

我在列表中调用index.1了30 个矩阵。我可以使用以下方法将它们组合成一个矩阵:index.30listnamedo.call

new.matrix = do.call(rbind, listname)

但是如何在矩阵中创建一个变量作为指标来显示每个观察最初来自哪个矩阵?

4

1 回答 1

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)
于 2012-09-16T11:42:18.250 回答