Search code examples
rdplyrtidyversetibblereadr

Preserving decimal data format when writing r tibble data to .txt file


I am trying to write a tidyverse tibble to a text file while maintaining decimal format in the out put file, but all write functions seem to convert decimal data with quite a few significant digits. The data looks like this:

> glimpse(data)
Rows: 125,784
Columns: 7
$ Lon      <dbl> -123.25, -123.25
$ Lat      <dbl> 38.25, 38.25
$ Year     <dbl> 2014, 2015
$ W        <dbl> 0.999998, 0.000000
$ X        <dbl> 0.000001, 0.500000
$ Y        <dbl> 0.000001, 0.500000
$ Z        <dbl> 0, 0

I tried the following:

options(scipen = 999)
options(pillar.sigfig = 6)
options(digits = 6)
num(data, sigfig = 6, notation = "dec")
options(digits = 6)
num(data, digits = 6, notation = "dec")

None of the above options seem to work and when I write the data to a .txt file as follows:

write_delim(data, file = "data.txt", col_names = T, delim = " ", eol = " \n")

I always get the following in my data.txt file:

Lon Lat Year W X Y Z 
-123.25 38.25 2014 0.999998 1e-6 1e-6 0 
-123.25 38.25 2015 0 0.5 0.5 0 

As can be seen above, numbers with greater than 1 significant figures or decimal places have been converted to scientific notation. Is there a way to get the data to print as is so that my data.txt file looks as follows:

Lon Lat Year W X Y Z 
-123.25 38.25 2014 0.999998 0.000001 0.000001 0 
-123.25 38.25 2015 0 0.5 0.5 0 

Solution

  • you can dplyr::mutate the data using across() and round() like:

    data %>% 
      mutate(across(is.numeric, round, 7))