[R] how to take multiple subsets from a matrix

dc896148 cyr.derek at gmail.com
Thu Mar 18 01:54:14 CET 2010


useR's
I have a matrix from which I want to take multiple subsets from, according
to a particular scheme I will now describe.  The matrix below (mat) is 5x5,
and I want to take 9 subsets of it, each of dimension 3x3.  The best way to
explain what the result should look like is with the following:
> dat <- c(3,6,1,9,12,9,2,10,6,5,3,13,1,4,8,9,4,6,10,11,2,7,3,5,10)
> miss <- c(2,8,10,16,23)
> dat[miss] <- NA
> mat <- matrix(dat,5,5)
> mat
     [,1] [,2] [,3] [,4] [,5]
[1,]    3    9    3   NA    2
[2,]   NA    2   13    4    7
[3,]    1   NA    1    6   NA
[4,]    9    6    4   10    5
[5,]   12   NA    8   11   10

I define a multidimensional array to hold the 9 subarrays I want:
> subarray <- array(0,dim=c(3,3,9))

I want to populate each 3x3 array within subarray with the value from mat,
taking the values from mat to be the center values of each array,
respectively.  so, excluding the edges of mat, there are 9 values to build
3x3 arrays from: 2,13,4,NA,1,6,6,4,10

The output for subarray should look like this:
[,,1]
     [,1] [,2] [,3]
[1,]    3    9    3
[2,]  NA    2   13
[3,]    1  NA    1
[,,2]
     [,1] [,2] [,3]
[1,]    9    3   NA
[2,]    2   13   4
[3,]  NA    1    6
[,,3]
     [,1] [,2] [,3]
[1,]    3  NA    2
[2,]   13   4    7
[3,]    1   6   NA
...
...
[,,9]
     [,1] [,2] [,3]
[1,]   1    6   NA
[2,]   4   10    5
[3,]   8   11  10

I hope this is clear.  Does anyone know a quick and efficient way to do this
in R?  I was thinking of FOR loops, but as my matrices get very large, this
process may take some time.  Any ideas?

Thank you in advance
dxc13
-- 
View this message in context: http://n4.nabble.com/how-to-take-multiple-subsets-from-a-matrix-tp1597411p1597411.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list