[R] The "less than" (<) operator doesnt seem to perform as expected
Petr Savicky
savicky at cs.cas.cz
Thu Feb 2 19:21:44 CET 2012
On Thu, Feb 02, 2012 at 10:00:58AM +0000, Jonas Hal wrote:
> The example here puzzles me. It seems like the < operator doesn't work as expected.
>
> > l <- 0.6
> > u <- seq(0.4, 0.7, 0.1)
> > u
> [1] 0.4 0.5 0.6 0.7
> > mygrid <- expand.grid("l" = l, "u" = u)
> > mygrid
> l u
> 1 0.6 0.4
> 2 0.6 0.5
> 3 0.6 0.6
> 4 0.6 0.7
> > mygridcollapsed <- mygrid[mygrid$l < mygrid$u, ]
> > mygridcollapsed
> l u
> 3 0.6 0.6
> 4 0.6 0.7
>
> In this little example I expect 'mygridcollapsed' only to return row 4 and for it to return row 3 seems wrong. The strange thing is it seems to work if I start the u-sequence at 0.5.
Hi.
As others pointed out, the problem is in different
rounding error of 0.6 and seq(0.4, 0.7, 0.1)[3]. Try
print(0.6, digits=20)
[1] 0.5999999999999999778
print(seq(0.4, 0.7, 0.1)[3], digits=20)
[1] 0.60000000000000008882
Use round(, digits=1) to force the same rounding in
seq(0.4, 0.7, 0.1) and in c(0.4, 0.5, 0.6, 0.7)
round(seq(0.4, 0.7, 0.1), digits=1) == c(0.4, 0.5, 0.6, 0.7)
Hope this helps.
Petr Savicky.
More information about the R-help
mailing list