[R] [External] replacing a value

Richard M. Heiberger rmh @end|ng |rom temp|e@edu
Wed Apr 6 06:47:10 CEST 2022


I believe you are not remembering that floating point numbers are not
exactly represented in decimal.
See FAQ 7.31

Here I have rounded a[4] to 12 places before comparing to 20.
The you get the answer you are looking for.

> a <- c(20, 20, 14.2375646029948, 19.9999999999999, 20, 20, 16.3092078677214,
+ 20, 20, 20, 20, 20, 20, 20, 20, 14.8590932408795, 16.178935255298,
+ 20, 20, 20, 20, 27.6404077886079, 20, 20, 20, 20, 20, 21.9857063037444,
+ 20, 20, 20, 20)
> a[1:6]
[1] 20.00000 20.00000 14.23756 20.00000 20.00000 20.00000
> print(a[1:6], digits=17)
[1] 20.000000000000000 20.000000000000000 14.237564602994800 19.999999999999901 20.000000000000000 20.000000000000000
> a[1:6] == 20
[1]  TRUE  TRUE FALSE FALSE  TRUE  TRUE
> a[1:6] - 20
[1]  0.000000e+00  0.000000e+00 -5.762435e+00 -9.947598e-14  0.000000e+00  0.000000e+00
> a[4] == 20
[1] FALSE
> round(a[1:6], digits=14) - 20
[1]  0.000000e+00  0.000000e+00 -5.762435e+00 -9.947598e-14  0.000000e+00  0.000000e+00
> round(a[1:6], digits=13) - 20
[1]  0.000000e+00  0.000000e+00 -5.762435e+00 -9.947598e-14  0.000000e+00  0.000000e+00
> round(a[1:6], digits=12) - 20
[1]  0.000000  0.000000 -5.762435  0.000000  0.000000  0.000000
> b <- a[1:6]
> b[round(b,digits=12) == 20] <- 0
> b
[1]  0.00000  0.00000 14.23756  0.00000  0.00000  0.00000
> 

> On Apr 06, 2022, at 00:18, ani jaya <gaaauul using gmail.com> wrote:
> 
>>> c(20, 20, 14.2375646029948, 19.9999999999999, 20, 20, 16.3092078677214,
>>> 20, 20, 20, 20, 20, 20, 20, 20, 14.8590932408795, 16.178935255298,
>>> 20, 20, 20, 20, 27.6404077886079, 20, 20, 20, 20, 20, 21.9857063037444,
>>> 20, 20, 20, 20)



More information about the R-help mailing list