[R] table and unique seems to behave differently

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Tue Dec 10 16:03:34 CET 2019


On 10/12/2019 3:53 a.m., Alain Guillet wrote:
> Hi,
> 
> I have a vector (see below the dput) and I use unique on it to get unique values. If I then sort the result of the vector obtained by unique, I see some elements that look like identical. I suspect it could be a matter of rounded values but table gives a different result: unlike unique output which contains "3.4  3.4", table has only one cell for 3.4.
> 
> Can anybody know why I get results that look like incoherent between the two functions?

dput() does some rounding, so it doesn't necessarily reproduce values 
exactly.  For example,

x <- c(3.4, 3.4 + 1e-15)
unique(x)
#> [1] 3.4 3.4
dput(x)
#> c(3.4, 3.4)
identical(x, c(3.4, 3.4))
#> [1] FALSE

If you really want to see exact values, you can use the "hexNumeric" 
option to dput():

dput(x, control = "hexNumeric")
#> c(0x1.b333333333333p+1, 0x1.b333333333335p+1)
identical(x, c(0x1.b333333333333p+1, 0x1.b333333333335p+1))
#> [1] TRUE

Duncan Murdoch



More information about the R-help mailing list