[R] Subset a floating point vector using all.equal?
Rui Barradas
ruipbarradas at sapo.pt
Thu May 30 12:34:28 CEST 2013
Hello,
You can write a helper function.
are.equal <- function(x, y, eps = .Machine$double.eps^0.5) abs(x - y) < eps
x[are.equal(x, 0.15)]
Hope this helps,
Rui Barradas
Em 30-05-2013 02:27, Peter Lomas escreveu:
> 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)]
>
> 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.
>
> Peter
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
More information about the R-help
mailing list