Search code examples
rdplyrcharacter

R: as.character removes trailing zeros of numbers. How to avoid


I have

kappa<-c(0.10, NA, 0.0740)

When I do

kappa %>% replace(is.na(.), "")

I get

> kappa %>% replace(is.na(.), "")
[1] "0.1"   ""      "0.074" 

The same when I do

> as.character(kappa)
[1] "0.1"   NA      "0.074"

How can I avoid (in the remove() case) the removal of the trailing zero? I would like to result to the following vector

"0.10", NA, "0.0740"

Solution

  • You are looking for format() with a nsmall argument as the number of digits.

    This number can be computed as the maximum of the base 10 logarithm of your numeric vector (but you obviously can enter any arbitrary value).

    Here is the code:

    kappa = c(0.10, NA, 0.0740)
    n_digits = max(abs(log(kappa)), na.rm=TRUE)
    format(kappa, nsmall=n_digits)
    #> [1] "0.100" "   NA" "0.074"
    

    Created on 2022-12-13 with reprex v2.0.2