[R] Splitting matrix into several small matrices
jim holtman
jholtman at gmail.com
Tue Jul 28 01:50:17 CEST 2009
Here is one way to do it:
> x
V1 V2 V3 V4 V5
[1,] 13 1 1 1 1
[2,] 12 0 0 0 0
[3,] 8 1 0 1 1
[4,] 9 0 1 0 0
[5,] 10 1 1 1 1
[6,] 3 0 1 0 0
[7,] 3 1 0 1 1
[8,] 6 1 1 1 1
> # create the row indices based on columns 2-3
> x.i <- split(seq(nrow(x)), paste(x[,2], x[,3]))
> x.i
$`0 0`
[1] 2
$`0 1`
[1] 4 6
$`1 0`
[1] 3 7
$`1 1`
[1] 1 5 8
> # now create a list of the matrices
> lapply(x.i, function(a) x[a,,drop=FALSE])
$`0 0`
V1 V2 V3 V4 V5
[1,] 12 0 0 0 0
$`0 1`
V1 V2 V3 V4 V5
[1,] 9 0 1 0 0
[2,] 3 0 1 0 0
$`1 0`
V1 V2 V3 V4 V5
[1,] 8 1 0 1 1
[2,] 3 1 0 1 1
$`1 1`
V1 V2 V3 V4 V5
[1,] 13 1 1 1 1
[2,] 10 1 1 1 1
[3,] 6 1 1 1 1
>
On Mon, Jul 27, 2009 at 6:46 PM, kathie<kathryn.lord2000 at gmail.com> wrote:
>
> Dear R users...
>
> I need to split this matrix(or dataframe), for example,
>
> z <- matrix(c(13,1,1,1,1,12,0,0,0,0,8,1,0,1,1,8,0,1,0,0,
> 10,1,1,1,1,3,0,1,0,0,3,1,0,1,1,6,1,1,1,1),8,5,byrow = T)
>
>
>> z
> [,1] [,2] [,3] [,4] [,5]
> [1,] 13 1 1 1 1
> [2,] 12 0 0 0 0
> [3,] 8 1 0 1 1
> [4,] 9 0 1 0 0
> [5,] 10 1 1 1 1
> [6,] 3 0 1 0 0
> [7,] 3 1 0 1 1
> [8,] 6 1 1 1 1
>
>
> (actually, z matrix is big, about 1000*15 matrix)
>
> to 4 matrices like this way,
>
>
> #- 1st matrix--------------------------------------
> 13 1 1 1 1
> 10 1 1 1 1
> 6 1 1 1 1
>
> #- 2nd matrix--------------------------------------
> 12 0 0 0 0
>
>
> #- 3rd matrix--------------------------------------
> 8 1 0 1 1
> 3 1 0 1 1
>
>
> #- 4th matrix--------------------------------------
> 9 0 1 0 0
> 3 0 1 0 0
>
>
>
> Any comments will be greatly appreciated.
>
> Kathryn Lord
> --
> View this message in context: http://www.nabble.com/Splitting-matrix-into-several-small-matrices-tp24689585p24689585.html
> Sent from the R help mailing list archive at Nabble.com.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
--
Jim Holtman
Cincinnati, OH
+1 513 646 9390
What is the problem that you are trying to solve?
More information about the R-help
mailing list