我有一个超过200列的矩阵,只有2行。我打算把这个矩阵分成4个不同的类别这取决于每一列对应的类别。我该如何使用条件语句呢,还是有其他的方法?例如,我在考虑首先确定每个类别。cat1 <- (matrix.name["第一行名称",i(每一列的位置])== " A " &matrix.name["第二行名称",i(每一列的位置])== " B ")我该如何使用cat1来打印一个新的矩阵?
像这样:
some_mtx <- matrix(c(rep('A', 10), rep('C',10), rep('B', 10), rep('D',10)), ncol = 20, byrow=TRUE)
some_mtx
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11] [,12] [,13] [,14]
[1,] "A" "A" "A" "A" "A" "A" "A" "A" "A" "A" "C" "C" "C" "C"
[2,] "B" "B" "B" "B" "B" "B" "B" "B" "B" "B" "D" "D" "D" "D"
[,15] [,16] [,17] [,18] [,19] [,20]
[1,] "C" "C" "C" "C" "C" "C"
[2,] "D" "D" "D" "D" "D" "D"
matrix(c(some_mtx[which(some_mtx =='A')], some_mtx[which(some_mtx == 'D')]), ncol = 10)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "A" "A" "A" "A" "A" "D" "D" "D" "D" "D"
[2,] "A" "A" "A" "A" "A" "D" "D" "D" "D" "D"
# or with `byrow=TRUE`
matrix(c(some_mtx[which(some_mtx =='A')], some_mtx[which(some_mtx == 'D')]), ncol = 10, byrow = TRUE)
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,] "A" "A" "A" "A" "A" "A" "A" "A" "A" "A"
[2,] "D" "D" "D" "D" "D" "D" "D" "D" "D" "D"
想象你的数据对象。