Long Numbers As A Character String

后端 未结 6 734
栀梦
栀梦 2020-12-01 23:40

As part of my dataset, one of the columns is a series of 24-digit numbers.

Example:

bigonumber <- 429382748394831049284934

When

6条回答
  •  感动是毒
    2020-12-02 00:14

    You can suppress the scientific notation with

    options(scipen=999)
    

    If you define the number then

    bigonumber <- 429382748394831049284934
    

    you can convert it into a string:

    big.o.string <- as.character(bigonumber)
    

    Unfortunately, this does not work because R converts the number to a double, thereby losing precision:

    #[1] "429382748394831019507712"
    

    The last digits are not preserved, as pointed out by @SabDeM. Even setting

    options(digits=22)
    

    doesn't help, and in any case 22 is the largest number that is allowed; and in your case there are 24 digits. So it seems that you will have to read the data directly as character or factor. Great answers have been posted showing how this can be achieved.

    As a side note, there is a package called gmp that allows using arbitrarily large integer numbers. However, there is a catch: they have to be read as characters (again, in order to prevent R's internal conversion into double).

    library(gmp)
    bigonumber <- as.bigz("429382748394831049284934")
    > bigonumber
    Big Integer ('bigz') :
    [1] 429382748394831049284934
    > class(bigonumber)
    [1] "bigz"
    

    The advantage is that you can indeed treat these entries as numbers and perform calculations while preserving all the digits.

    > bigonumber * 2
    #Big Integer ('bigz') :
    #[1] 858765496789662098569868
    

    This package and my answer here may not solve your problem, because reading the numbers directly as characters is an easier way to achieve your goal, but I thought I might post this anyway as an information for users who may need to use large integers with more than 22 digits.

提交回复
热议问题