Search code examples
rxlsxdata-importreadxl

read_excel truncates numbers in spite of setting digits option


I am trying to read an excel file into R with read_excel() function from the "readxl" package. Numbers in cells in the excel file have 3 decimal places, e.g. 0,684 1,338 74,296. In the R dataframe the same numbers are 0,684 1,34 74,3. Why did only 3 digits remain?

I have set options(digits=5) (tried different values as well) .

I have also tried to read_excel("file.xlsx", col_types = c("text", "text", "text")) (which gave me strings: 74.296000000000006 1.3380000000000001 0.68400000000000005) and then convert to numbers withas.numeric(), but again the numbers have been truncated: 0,684 1,34 74,3.

Please, let me know if you know the reason :)


Solution

  • Be careful to not confuse "how many digits are there" vs. "how many digits R is showing you". It's hard to know for sure without seeing your code, but I suspect you are printing a tibble, something like this:

    library(readxl)
    my_junk <- read_excel("~/Downloads/test.xlsx")
    print(my_junk)
    #> # A tibble: 3 x 1
    #>    test
    #>   <dbl>
    #> 1 0.684
    #> 2 1.000
    #> 3 1.00
    

    The default print method for tibbles shows only a few significant digits. And it doesn't seem to respond to the digits setting in options. However if we convert it to a data.frame you will see that the digits were there all along:

    library(dplyr)
    my_junk %>%
      data.frame %>%
      print( digits = 7)  
    #>       test
    #> 1 0.684000
    #> 2 0.999950
    #> 3 1.000001
    

    So your digits are likely there, they just aren't displaying.