简体   繁体   English

合并来自许多矩阵的选定列

[英]Combine selected columns from many matrices

I am trying to accomplish the following task to get to matrix d : 我正在尝试完成以下任务以获得矩阵d

d1<-matrix(as.factor(rep(sample(1:10,10,T),5)),ncol=5)
d2<-matrix(as.factor(rep(sample(1:10,10,T),5)),ncol=5)
d3<-matrix(as.factor(rep(sample(1:10,10,T),5)),ncol=5)

d<-cbind(
  cbind(d1[,2],d1[,5]),
  cbind(d2[,2],d2[,5]),
  cbind(d3[,2],d3[,5])
)

But for many matrices d1...dn, say. 但对于许多矩阵d1 ... dn,比如说。

More generally I would like to select the same column numbers from a series of matrices and append into a single matrix. 更一般地说,我想从一系列矩阵中选择相同的列号并附加到单个矩阵中。 The focus of this task is on combining, not creating the matrices. 这项任务的重点是合并,而不是创建矩阵。 The factor-type column vectors should be preserved. 应保留因子类型列向量。

I thought about something along the lines of 我想到了类似的东西

d<-matrix(nrow=10)
dl<-list(d1,d2,d3)
for (i in 1:3){
  d<-cbind(d,dl[[i]][,2],dl[[i]][,5])
}

But maybe there is a better way. 但也许有更好的方法。

You can create a list of your matrices and use do.call and lapply to get what you want: 您可以创建一个矩阵list ,并使用do.calllapply来获得您想要的内容:

matList <- list(d1, d2, d3)
do.call(cbind, lapply(matList, function(x) x[, c(2, 5)]))
#       [,1] [,2] [,3] [,4] [,5] [,6]
#  [1,] "3"  "3"  "3"  "3"  "10" "10"
#  [2,] "4"  "4"  "2"  "2"  "3"  "3" 
#  [3,] "6"  "6"  "7"  "7"  "7"  "7" 
#  [4,] "10" "10" "4"  "4"  "2"  "2" 
#  [5,] "3"  "3"  "8"  "8"  "3"  "3" 
#  [6,] "9"  "9"  "5"  "5"  "4"  "4" 
#  [7,] "10" "10" "8"  "8"  "1"  "1" 
#  [8,] "7"  "7"  "10" "10" "4"  "4" 
#  [9,] "7"  "7"  "4"  "4"  "9"  "9" 
# [10,] "1"  "1"  "8"  "8"  "4"  "4" 

By the way, the data type in your matrix is character , not factor . 顺便说一下,矩阵中的数据类型是character ,而不是factor See the help page at ?matrix where you will find the following: 请参阅?matrix的帮助页面,您将在其中找到以下内容:

The method for data frames will return a character matrix if there is only atomic columns and any non-(numeric/logical/complex) column, applying as.vector to factors and format to other non-character columns. 如果只有原子列和任何非(数字/逻辑/复杂)列,将as.vector应用于因子并格式化为其他非字符列,则数据帧的方法将返回字符矩阵。

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

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