[R] Converting indices of a matrix subset

Steve Lianoglou mailinglist.honeypot at gmail.com
Thu Jul 9 15:53:02 CEST 2009


Hi Nathan,

On Jul 8, 2009, at 10:20 PM, Nathan S. Watson-Haigh wrote:

> I have two matrices:
>
>> m1 <- matrix(1,4,4)
>> m1
>     [,1] [,2] [,3] [,4]
> [1,]    1    1    1    1
> [2,]    1    1    1    1
> [3,]    1    1    1    1
> [4,]    1    1    1    1
>
>> m2 <- matrix(0,3,3)
>> diag(m2) <- 1
>> m2
>     [,1] [,2] [,3]
> [1,]    1    0    0
> [2,]    0    1    0
> [3,]    0    0    1
>
> I want to get indicies from m2 such that they match indicies as  
> though they came
> from the lower right of m1. Here's how things work:
>
>> ind1 <- which(m1 == 1)
>> ind1
> [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16
>> ind2 <- which(m2 == 1)
>> ind2
> [1] 1 5 9
>
>
> I would like ind2 to be offset so they look like indicies from the  
> lower right
> of m1:
>> ind2
> [1] 6 11 16


I have written some utility functions I use often[1], and have  
"sub2ind" function that works in a similar fashion to the MATLAB  
function of the same name. It's somehow long and convoluted because  
you can send in your arguments 12 different ways from sunday, so:

sub2ind <- function(x, y, nrow, ncol=NULL) {
   ## Returns a linear index for the (x,y) coordinates passed in.
   if (is.matrix(x) || is.data.frame(x)) {
     stopifnot(ncol(x) == 2)
     if (!missing(y)) {
       if (missing(nrow)) {
         nrow <- y
       } else {
         ncol <- nrow
         nrow <- y
       }
     }
     y <- x[,2]
     x <- x[,1]
   }

   if (is.matrix(nrow)) {
     d <- dim(nrow)
     nrow <- d[1]
     ncol <- d[2]
   } else if (is.null(ncol)) {
     stop("Dimensions of matrix under-specified")
   }

   # Sanity check to ensure we got each var doing what it should be  
doing
   if (length(x) != length(y) || length(nrow) != 1 || length(ncol) !=  
1) {
     stop("I'm confused")
   }

   ((x - 1) + ((y - 1) * nrow)) + 1

}

R> m1 <- matrix(1,4,4)
R> m2 <- matrix(0,3,3)
R> ind2 <- which(m2 == 1, arr.ind=T) + 1
R> ind2
      row col
[1,]   2   2
[2,]   3   3
[3,]   4   4

R> my.ind2 <- sub2ind(ind2, nrow=4, ncol=4)
# my.ind2 <- sub2ind(ind2[,1], ind2[,2], 4, 4)
# my.ind2 <- sub2ind(ind2[,1], ind2[,2], m1)
# my.ind2 <- sub2ind(ind2, m1)
R> my.ind2
[1]  6 11 16

I think that gets you to where you want to be :-)

-steve

[1] They can be found here if your intersted, there isn't much  
documentation there, but I'll fix that some time later :-)
http://github.com/lianos/ARE.utils/tree/master

--
Steve Lianoglou
Graduate Student: Physiology, Biophysics and Systems Biology
Weill Medical College of Cornell University

Contact Info: http://cbio.mskcc.org/~lianos




More information about the R-help mailing list