[R] Subset a floating point vector using all.equal?

David Winsemius dwinsemius at comcast.net
Thu May 30 07:37:22 CEST 2013


On May 29, 2013, at 6:27 PM, Peter Lomas wrote:

> Hello,
>
> I have a whole bunch of data to two decimal places.  I've done some
> arithmetic with them, so floating point becomes an issue.
>
> x <- c(1, 0.15,(0.1+.05),0.4)
>
> I want to do something like this:
>
> x[x==0.15]
>
> But you'll notice that is troublesome with the well known floating  
> point
> issue.  So really I need to do something like this:
>
> x[all.equal(x, 0.15)]

x[ zapsmall(x-0.15)==0 ]

>
> But that doesn't work because all.equal wants to compare objects and  
> not
> each element.
>
> I could do:
>
> x[round(x,2) ==0.15]
>
> It seems to work in this case, but as I've been working with my data  
> I'm
> concerned its unreliable.  What is the most efficient way of  
> subsetting
> data using a machine-tolerance equal numeric value?
>
> Thanks R-Helpers.
>


David Winsemius, MD
Alameda, CA, USA



More information about the R-help mailing list