Wednesday 11 September 2013

subsetting matrix with id from another matrix

subsetting matrix with id from another matrix

I am just beginning to learn R, so I apologize in advance for the
ambiguity of my syntax as well as the apparent simplicity. Also, if there
is a better way of doing the below, I really appreciate any suggestions
and recommendations.
I would like to subset the data of one matrix using data in a second
matrix. The columns of one matrix is labeled. For example,
area1 <-
c(9836374,635440,23018,833696,936079,1472449,879042,220539,870581,217418,552303,269359,833696,936079,1472449,879042,220539,870581,
833696,936079,1472449,879042,220539,870581)
id <- c(1,2,5,30,31,34,1,2,5,1,2,5,1,2,5,30,31,34,51,52,55,81,82,85)
mat1 <- matrix(area1, ncol=3, byrow=T)
mat2 <- matrix(id, ncol=3, byrow=T)
dimnames(mat1) <-list(NULL, c("a1","a2","a3"))
mat2 contains the ids for mat1, so the dimensions of the matrix are the
same (i.e., mat1[1,1] identifies mat2[1,1]. What I want is to create
submatrices of mat1 when the row with values c(1, 2, 5) shows up in mat2.
In this present mini example, submatrix 1 would have 2 rows of data,
submatrix 2 and 3 have 1 row each, and submatrix 4 would have 4 rows of
data from mat1. The number of rows between subsequent rows with 1,3,5
varies. Does this make sense?
Originally, the matrices were transformed from a dataframe, with id in one
column and area in a second column. I couldn't find a way to subset
variable rows between rows of 1 within a dataframe, which is why I
switched to a matrix.

No comments:

Post a Comment