Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write.csv precision R

Tags:

rounding

r

csv

I am dealing with very precise numbers (maximum number of digits).

I noticed that write.csv(x) in R sometimes round the number.

Has anyone noticed something like that? What is the default number of digits saved?

like image 221
richpiana Avatar asked Jan 03 '23 15:01

richpiana


1 Answers

As written in the documentation,

In almost all cases the conversion of numeric quantities is governed by the option "scipen" (see options), but with the internal equivalent of digits = 15. For finer control, use format to make a character matrix/data frame, and call write.table on that.

So the simple solution is to change the options, i.e.

options(digits = DESIRED_VALUE)

and the customized solution is to convert your variables to character type with format, e.g.

dat <- mtcars
dat$wt <- format(dat$wt, digits = 20)

and save it like this. Notice however then when using computers we are always dealing with rounded numbers (see Gldberg, 1991, What Every Computer Scientist Should Know About Floating-Point Arithmetic), and you could find tricky outcomes do to the computer precision, e.g.

format(2.620, digits = 20)
## [1] "2.6200000000000001066"

So there is nothing "bad" with rounded values as you probably need them only to be precise up to some number of decimal places. Moreover, your measurements are also affected with measurement errors, so the precision can be illusory.

like image 166
Tim Avatar answered Jan 14 '23 15:01

Tim