R:按矩阵的第一列进行拆分

时间:2018-07-31 14:23:41

标签: arrays r matrix split

我有一个8 x 3的矩阵,我想分成3个矩阵的数组,每个矩阵有3列,但行数不同。第一列中的字符串指示应在何处进行拆分。

mat
#     [,1] [,2]  [,3] 
#[1,] "a"  "5"   "7"  
#[2,] "a"  "33"  "45" 
#[3,] "b"  "23"  "63" 
#[4,] "b"  "25"  "245"
#[5,] "b"  "78"  "718"
#[6,] "b"  "64"  "94" 
#[7,] "c"  "34"  "56" 
#[8,] "c"  "444" "32"  

3 个答案:

答案 0 :(得分:2)

如果确实希望将其作为数组,则可以使用\n

abind

答案 1 :(得分:0)

使用split()分解矩阵,然后使用lapply()重塑结果段:

lapply(split(mat, mat[,1]), function(x) matrix(x, ncol=3))
$a
     [,1] [,2] [,3]
[1,] "a"  "5"  "7" 
[2,] "a"  "33" "45"

$b
     [,1] [,2] [,3]
[1,] "b"  "23" "63"

$c
     [,1] [,2]  [,3]
[1,] "c"  "34"  "56"
[2,] "c"  "444" "32"

数据(从OP中略有截断):

mat <- matrix(c("a", "5", "7", 
                "a", "33", "45", 
                "b", "23", "63", 
                "c","34", "56", 
                "c", "444", "32"), 
              byrow=T, ncol=3)
mat
     [,1] [,2]  [,3]
[1,] "a"  "5"   "7" 
[2,] "a"  "33"  "45"
[3,] "b"  "23"  "63"
[4,] "c"  "34"  "56"
[5,] "c"  "444" "32"

答案 2 :(得分:0)

lapply(unique(mat[,1,drop=FALSE]), function(x) subset(mat, x == mat[,1,drop=FALSE]))

或者,如果您希望能够使用mat的第一列的值访问结果:

res <- sapply(unique(mat[,1,drop=FALSE]), function(x) subset(mat, x == mat[,1,drop=FALSE]))
res[["a"]]