Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R How to use which() with floating point values?

Tags:

r

I have run into the same problem as described at R which () function returns integer(0)

price = seq(4,7, by=0.0025)
allPrices = as.data.frame(price)
lookupPrice = 5.0600
which(allPrices$price == lookupPrice)

The which() statement outputs integer(0), indicating no match. It should output 425, the matching row number in that sequence.

I understand that this is a floating point issue. The link suggests using all.equal(x,y) in some manner.

How do I incorporate the all.equal() function into the which() statement, so that I get the row number in allPrices that matches lookupPrice (in this case, 5.06)?

Is there some other approach? I need the row number, because values in other columns at that price will be modified.

like image 238
Doug Edmunds Avatar asked Jul 20 '17 05:07

Doug Edmunds


1 Answers

A manual approach to this involves specifying the tolerance for the comparison and doing:

# tol = 1e-7: comparison will be TRUE if numbers are equal up to 
#   7 decimal places
tol = 1e-7
which(abs(allPrices$price - lookupPrice) < tol)
like image 148
Marius Avatar answered Oct 23 '22 13:10

Marius