[R] How do I get the row indices?
Marc Schwartz (via MN)
mschwartz at mn.rr.com
Fri Sep 16 20:05:38 CEST 2005
On Fri, 2005-09-16 at 10:34 -0700, Martin Lam wrote:
> I was wondering if it's possible to get the row
> numbers from a filtering. Here's an example:
> # give me the rows with sepal.length == 6.2
> # output
> Sepal.Length Sepal.Width Petal.Length Petal.Width
> 69 6.2 2.2 4.5 1.5
> 98 6.2 2.9 4.3 1.3
> 127 6.2 2.8 4.8 1.8
> 149 6.2 3.4 5.4 2.3
> What I really want is that it return the row numbers:
> 69, 98, 127, 149.
> Thanks in advance,
First: Be very, very careful when performing exact equalities on
floating point numbers. They won't always result in the answer you
expect. For more information see R FAQ 7.31: Why doesn't R think these
numbers are equal?
See ?all.equal, ?sapply and ?which. Here is a possible vectorized
> which(sapply(iris[, 1], function(x) isTRUE(all.equal(x, 6.2))))
 69 98 127 149
The above applies isTRUE(all.equal(x, 6.2)) for each element 'x' in
iris[, 1], returning the indices of the TRUE results for the near
equality comparison, based upon the tolerance argument in all.equal().
More information about the R-help