Togaware DATA MINING
Desktop Survival Guide
by Graham Williams
Google

Finding Index of Elements

To obtain a list of row indicies for a matrix or data frame for those rows meeting some criteria we can use the which function:

> which(iris$Sepal.Length == 6.2)
[1]  69  98 127 149

Conditions can be combined, in which case it becomes useful to use the with function, which specifies a dataset with which to evaluate the expression:

> with(iris, which(Sepal.Length < 6.2 & Sepal.Width > 4))
[1] 16 33 34

Similarly for a matrix:

> A <- matrix(c(1:19, 10), 4, 5)
> A
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    5    9   13   17
[2,]    2    6   10   14   18
[3,]    3    7   11   15   19
[4,]    4    8   12   16   10
> which(A == 11, arr.ind = TRUE)
     row col
[1,]   3   3
>  which(A == 14, arr.ind = TRUE)
     row col
[1,]   2   4
>  which(A == 10, arr.ind = TRUE)
     row col
[1,]   2   3
[2,]   4   5



Copyright © Togaware Pty Ltd
Support further development through the purchase of the PDF version of the book.
The PDF version is a formatted comprehensive draft book (with over 800 pages).
Brought to you by Togaware. This page generated: Sunday, 22 August 2010