[R] Splitting a matrix
Megh Dal
megh700004 at yahoo.com
Thu Sep 16 09:42:36 CEST 2010
Hi, I was trying to split the following matrix "dat":
> set.seed(1)
> dat <- matrix(rnorm(4*16), 4, 16)
> dat
[,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10] [,11]
[1,] -0.6264538 0.3295078 0.5757814 -0.62124058 -0.01619026 0.91897737 0.61982575 -0.4781501 0.38767161 -0.3942900 -0.1645236
[2,] 0.1836433 -0.8204684 -0.3053884 -2.21469989 0.94383621 0.78213630 -0.05612874 0.4179416 -0.05380504 -0.0593134 -0.2533617
[3,] -0.8356286 0.4874291 1.5117812 1.12493092 0.82122120 0.07456498 -0.15579551 1.3586796 -1.37705956 1.1000254 0.6969634
[4,] 1.5952808 0.7383247 0.3898432 -0.04493361 0.59390132 -1.98935170 -1.47075238 -0.1027877 -0.41499456 0.7631757 0.5566632
[,12] [,13] [,14] [,15] [,16]
[1,] -0.6887557 -0.1123462 0.3411197 -0.3672215 2.40161776
[2,] -0.7074952 0.8811077 -1.1293631 -1.0441346 -0.03924000
[3,] 0.3645820 0.3981059 1.4330237 0.5697196 0.68973936
[4,] 0.7685329 -0.6120264 1.9803999 -0.1350546 0.02800216
I want to split above one into 4 matrices (probably can be confined into a list) wherein 1st matrix consists of columns 1-4, 2nd matrix consists column 5-8 etc. Here I tried following:
> lapply(split(t(dat), c(4,8,12,16), drop=F), function(x) return(t(matrix(x, 4, 4))))
$`4`
[,1] [,2] [,3] [,4]
[1,] -0.6264538 -0.01619026 0.38767161 -0.1123462
[2,] 0.1836433 0.94383621 -0.05380504 0.8811077
[3,] -0.8356286 0.82122120 -1.37705956 0.3981059
[4,] 1.5952808 0.59390132 -0.41499456 -0.6120264
$`8`
[,1] [,2] [,3] [,4]
[1,] 0.3295078 0.91897737 -0.3942900 0.3411197
[2,] -0.8204684 0.78213630 -0.0593134 -1.1293631
[3,] 0.4874291 0.07456498 1.1000254 1.4330237
[4,] 0.7383247 -1.98935170 0.7631757 1.9803999
$`12`
[,1] [,2] [,3] [,4]
[1,] 0.5757814 0.61982575 -0.1645236 -0.3672215
[2,] -0.3053884 -0.05612874 -0.2533617 -1.0441346
[3,] 1.5117812 -0.15579551 0.6969634 0.5697196
[4,] 0.3898432 -1.47075238 0.5566632 -0.1350546
$`16`
[,1] [,2] [,3] [,4]
[1,] -0.62124058 -0.4781501 -0.6887557 2.40161776
[2,] -2.21469989 0.4179416 -0.7074952 -0.03924000
[3,] 1.12493092 1.3586796 0.3645820 0.68973936
[4,] -0.04493361 -0.1027877 0.7685329 0.02800216
However this is not that which I wanted to get. Any idea on the proper code to doing that?
Thanks
More information about the R-help
mailing list