rcsvroundingreadr

How to round numbers in R with several zeros before the last digit and correctly exporting to .csv file?


I'm having problems when rounding numbers with many zeros before the last digit in R using the function round(). They appear to be correctly rounded in R the output, but when I export the rounded numbers into a .csv file using readr::write_excel_csv() they are shown as if they were not rounded. Example:

a <- c(-0.28866000000000003, 0.28372000000000003)

round(a, digits = 5)
[1] -0.28866  0.28372

Results in .csv file same as "a".

Does somebody know why?


Solution

  • If you want to set the number of decimals for multiple vectors that you would like to be converted into columns in your csv-file, you can use the following approach:

    #----------
    # Load packages
    #----------
    library(readr)
    library(dplyr)
    
    #----------
    # Generate exemplary vectors
    #----------
    a <- c(-0.28866000000000003, 0.28372000000000003)
    b <- c(-0.46866000000000003, 0.46372000000000003)
    
    #----------
    # Make data.frame from vectors & set decimal options for columns 
    #----------
    df <- data.frame (a, b) %>%
      mutate (across(1:2, .fns = function(x) {format(round(x, 5), nsmall = 5)}))
    
    #----------
    # Save as csv-file
    #----------
    write_excel_csv(df, "your_path/df.csv", delim = ";")