简体   繁体   English

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

[英]R: splitting a matrix by its first column

I have an 8 x 3 matrix that I want to split into an array of 3 matrices, each with 3 columns but different number of rows. 我有一个8 x 3的矩阵,我想分成3个矩阵的数组,每个矩阵有3列,但行数不同。 The strings in the first column indicates where the split should occurs. 第一列中的字符串指示应在何处进行拆分。

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"  

If you do want it as an array, you can use abind 如果确实要将其作为数组,则可以使用abind

splits <- split(seq(nrow(mat)), mat[, 1])
splits <- lapply(splits, function(x) mat[c(x, rep(NA, max(lengths(splits)) - length(x))),])
library(abind)
do.call(abind, list(splits, along = 3))

# , , a
# 
#      [,1] [,2] [,3]
# [1,] "a"  "5"  "7" 
# [2,] "a"  "33" "45"
# 
# , , b
# 
#      [,1] [,2] [,3]
# [1,] "b"  "23" "63"
# [2,] NA   NA   NA  
# 
# , , c
# 
#      [,1] [,2]  [,3]
# [1,] "c"  "34"  "56"
# [2,] "c"  "444" "32"

Use split() to break up the matrix, and then lapply() to reshape the resulting segments: 使用split()分解矩阵,然后使用lapply()调整结果段的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"

Data (slightly truncated from OP): 数据(从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"
lapply(unique(mat[,1,drop=FALSE]), function(x) subset(mat, x == mat[,1,drop=FALSE]))

or, if you would like to be able to access the results using the values of the first column of mat: 或者,如果您希望能够使用mat的第一列的值访问结果:

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

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

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