[R] search through a matrix

David Winsemius dwinsemius at comcast.net
Tue Apr 21 14:45:41 CEST 2009


On Apr 21, 2009, at 8:33 AM, onyourmark wrote:

>
> Thanks very much.
>
> I don't really understand the row() function. I looked in the  
> reference but
> I don't really get it. It says:
> Description
> Returns a matrix of integers indicating their row number in a matrix- 
> like
> object, or a factor indicating the row labels.
>
> Usage
> row(x, as.factor = FALSE)
>
> Arguments
> x a matrix-like object, that is one with a two-dimensional dim.
>
> I don't understand what row() does.

It returns a matrix of the same size as its arguments populated with  
the row numbers instead of the matrix elements.
>
>
> And in the example in the documentation it says:
> x <- matrix(1:12, 3, 4)

Now try row(x)

>
> # extract the diagonal of a matrix
> dx <- x[row(x) == col(x)]
> dx
> [1] 1 5 9
>
> I thought the single square bracket notation accepts a pair  
> separated by a
> comma but I don't see how
> row(x)==col(x) produces that?

The single square bracket notation can be used as [r,c] or  without  
the comma which requires a logical index. In the second method the  
matrix entries get processed serially, column-wise.

 > x <- matrix(1:12, 3, 4)
 > x[TRUE]
  [1]  1  2  3  4  5  6  7  8  9 10 11 12
 > row(x)
      [,1] [,2] [,3] [,4]
[1,]    1    1    1    1
[2,]    2    2    2    2
[3,]    3    3    3    3

-- 
David Winsemius, MD
Heritage Laboratories
West Hartford, CT




More information about the R-help mailing list