简体   繁体   English

R:将矩阵转换为子矩阵列表

[英]R: Convert matrix to list of submatrices

I have a matrix m, and I want to convert it to a list l where every list item is a submatrix of m consisting of x rows of m. 我有一个矩阵m,我想将其转换为列表l,其中每个列表项都是m的子矩阵,该矩阵由m的x行组成。

Like this: 像这样:

m <- matrix(sample(15,60,T),12)
l <- list(m[1:3,],m[4:6,],m[7:9,],m[10:12,])

I'm certain that there's a simple and more generic solution to this, but still being new to RI can't find it. 我敢肯定有一个简单且通用的解决方案,但是对于RI来说还是新手。 I thought about using lapply, but don't really know how. 我曾考虑过使用lapply,但实际上并不知道如何使用。 Any pointers in the right direction would be greatly appreciated. 朝正确方向的任何指针将不胜感激。

The split function is very useful here: 拆分功能在这里非常有用:

lapply(split(m,rep(c(1:3),each=4)),matrix,nrow=4)

Or more generally, 或更笼统地说,

n = 3
lapply(split(m,rep(c(1:n),each=(nrow(m)/n))),matrix,nrow(m)/n)

Just proceed as you did in your question using Map to iterate on the beginning index and finishing index: 就像您在问题中所做的那样,使用Map来迭代开始索引和结束索引:

p = 3
Map(function(u,v) m[u:v,], seq(1,nrow(m),p), seq(p,nrow(m),p))

#[[1]]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]   14    8    5   10    9
#[2,]   10    4    5    7    8
#[3,]    3    3    6    7    3

#[[2]]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    4    8   12    1    1
#[2,]    4    2   13    1   11
#[3,]    6    2    4    1   12

#[[3]]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]   11   12    8    5    7
#[2,]    3    6    2    6    2
#[3,]   13   13   10    7   12

#[[4]]
#     [,1] [,2] [,3] [,4] [,5]
#[1,]    9    7   12    8    9
#[2,]   10    8   13   14   13
#[3,]   12    6   11    4   11

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

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