[R] Problem with long number (from character to numeric class)

Marc Schwartz marc_schwartz at me.com
Wed Feb 9 15:12:34 CET 2011


On Feb 9, 2011, at 6:15 AM, PtitBleu wrote:

> 
> Hello,
> 
> I have a text file with one column containing long number but stored as
> string.
> I download the file with read.table (and colClass) and the first row of this
> column is :
> 
> "095842087016731010"
> 
> As I need to make some calculations with these numbers, I tried to convert
> them using as.numeric.
> But then I get
> as.numeric("095842087016731010")
> 95842087016731008
> 
> I understand the disappearing of the first 0 but I don't understand the
> substitution of the last 0 by 8.
> 
> Is there a way to avoid that ?
> Thanks in advance,
> Ptit Bleu. 

I get:

> as.numeric("095842087016731010")
[1] 9.584209e+16

# See ?as.character

> as.character(as.numeric("095842087016731010"))
[1] "95842087016731008"


I suspect you would need to look at using one of the R packages that support arbitrary/infinite precision representations if you need to deal with very large integers. Perhaps look at gmp and Rmpfr.

You are hitting R's limit of 15 significant digits, resulting in the loss of precision in the internal representation of the number, which is in turn, presented in the resultant coercion.

HTH,

Marc Schwartz



More information about the R-help mailing list