0

I am reading a large numeric data from csv. The values have trailing zeroes. When importing the data using read.csv, additional digits are appended to the end of the number.

Reproducible example:

> options(digits = 22)
> number <- as.character("19.745130761412300000000000000000")
> print(number)
[1] "19.745130761412300000000000000000"

> write.csv(number, "number.csv")
> read.csv("number.csv")
  X                  x
1 1 19.745130761412302

Note the 02 at the end of x.

This behaviour also occurs when using as.numeric:

> number <- as.character("19.745130761412300000000000000000")
> print(number)
[1] "19.745130761412300000000000000000"
> as.numeric(number)
[1] 19.745130761412302

How can I avoid the extra digits when importing many data? Removing the trailing zeroes prior to read.csv is not an option. Any help would be greatly appreciated.

Thanks,

Chris

  • 1
    R can't track that many digits accurately (which is really just a limit of the standard numeric "double" variable type). What are you doing that so many digits are required? Are they really numeric values to you? – MrFlick Feb 22 '18 at 16:12
  • 1
    Related: [why are these numbers not equal](https://stackoverflow.com/questions/9508518/why-are-these-numbers-not-equal) and [how many decimals of pi do we need](https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/) – MrFlick Feb 22 '18 at 16:16
  • Try setting this option before reading. `options(scipen = 999)` – giraffehere Feb 22 '18 at 16:19
  • @giraffehere R 3.4.3, Windows 10. The result still ends with 02. – Rui Barradas Feb 22 '18 at 16:22

1 Answers1

0

Use numerals = "no.loss" :

write.csv("19.745130761412300000000000000000", "number.csv")
dd <- read.csv("number.csv", numerals = "no.loss")

print(dd, digits = 22)
##   X                                 x
## 1 1 19.745130761412300000000000000000

str(dd)
## 'data.frame':   1 obs. of  2 variables:
##  $ X: int 1
##  $ x: Factor w/ 1 level "19.745130761412300000000000000000": 1

See the numerals argument in ?type.convert for details.

G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341