Search code examples
rcharacternumber-formatting

How to avoid number rounding when using as.numeric() in R?


I am reading well structured, textual data in R and in the process of converting from character to numeric, numbers lose their decimal places.

I have tried using round(digits = 2) but it didn't work since I first had to apply as.numeric. At one point, I did set up options(digits = 2) before the conversion but it didn't work either.

Ultimately, I desired to get a data.frame with its numbers being exactly the same as the ones seen as characters.

I looked up for help here and did find answers like this, this, and this; however, none really helped me solve this issue.

How will I prevent number rounding when converting from character to numeric?

Here's a reproducible piece of code I wrote.

library(purrr)
my_char = c("      246.00    222.22    197.98    135.10    101.50     86.45
            72.17     62.11     64.94     76.62    109.33    177.80")

# Break characters between spaces
my_char = strsplit(my_char, "\\s+")

head(my_char, n = 2)
#> [[1]]
#>  [1] ""       "246.00" "222.22" "197.98" "135.10" "101.50" "86.45" 
#>  [8] "72.17"  "62.11"  "64.94"  "76.62"  "109.33" "177.80"

# Convert from characters to numeric.
my_char = map_dfc(my_char, as.numeric)


head(my_char, n = 2)
#> # A tibble: 2 x 1
#>      V1
#>   <dbl>
#> 1    NA
#> 2   246

# Delete first value because it's empty
my_char = my_char[-1,1]

head(my_char, n = 2)
#> # A tibble: 2 x 1
#>      V1
#>   <dbl>
#> 1  246 
#> 2  222.

Solution

  • It's how R visualize data in a tibble.

    The function map_dfc is not rounding your data, it's just a way R use to display data in a tibble.

    If you want to print the data with the usual format, use as.data.frame, like this:

    head(as.data.frame(my_char), n = 4)
           V1
    #>1  246.00
    #>2  222.22
    #>3  197.98
    #>4  135.10
    

    Showing that your data has not been rounded.

    Hope this helps.