# [R] replacing a value

Bill Dunlap w||||@mwdun|@p @end|ng |rom gm@||@com
Wed Apr 6 17:03:38 CEST 2022

```The confusion comes from dput() not distinguishing between numbers that are
quite close to each other.  E.g.,

> x <- 20 - (0:12)*.Machine\$double.eps
> x == 20
[1]  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE
FALSE FALSE
> diff(x)
[1]  0.000000e+00  0.000000e+00  0.000000e+00  0.000000e+00  0.000000e+00
0.000000e+00
[7]  0.000000e+00  0.000000e+00 -3.552714e-15  0.000000e+00  0.000000e+00
0.000000e+00
>
> dput(x)
c(20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20)

You have to use dput's control="digits17" or "exact" to avoid this rounding:

> dput(x, control="digits17")
c(20, 20, 20, 20, 20, 20, 20, 20, 20, 19.999999999999996,
19.999999999999996,
19.999999999999996, 19.999999999999996)
> dput(x, control="exact")
c(0x1.4p+4, 0x1.4p+4, 0x1.4p+4, 0x1.4p+4, 0x1.4p+4, 0x1.4p+4,
0x1.4p+4, 0x1.4p+4, 0x1.4p+4, 0x1.3ffffffffffffp+4, 0x1.3ffffffffffffp+4,
0x1.3ffffffffffffp+4, 0x1.3ffffffffffffp+4)

The solution to your original problem is to specify a small range of values
around 20
that you wish to change to zero.  E.g.,
a[ abs(a-20) < 20*.Machine\$double.eps ] <- 0

-Bill

On Tue, Apr 5, 2022 at 7:48 PM ani jaya <gaaauul using gmail.com> wrote:

> Dear R-Help,
>
> I try to change a specific value here by following these:
>
> https://www.journaldev.com/39695/replace-in-r
>
> https://stackoverflow.com/questions/5824173/replace-a-value-in-a-data-frame-based-on-a-conditional-if-statement
>
> https://stackoverflow.com/questions/54615462/how-to-replace-certain-values-in-a-specific-rows-and-columns-with-na-in-r
> ..and many more
>
> however, it is not change anything. I believe it "should" be easy but
> I think I am missing something. I am afraid it is my system that has a
> problem but restarting r is not solve the problem.
> I just want to change 20 to 0 in my data.
>
> > dput(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)
>
> what I did:
> a[a==20]<-0 #fail
> a<-replace(a,a==20,0) #fail
> a[which(a==20)]<-0 #fail
>
> > sessionInfo()
> R version 4.1.2 (2021-11-01)
> Platform: x86_64-w64-mingw32/x64 (64-bit)
> Running under: Windows 10 x64 (build 19043)
>
> Matrix products: default
>
> locale:
> [1] LC_COLLATE=English_United States.1252  LC_CTYPE=English_United
> States.1252
> [3] LC_MONETARY=English_United States.1252 LC_NUMERIC=C
> [5] LC_TIME=English_United States.1252
> system code page: 949
>
> Best,
> Ani
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help