Search code examples
rformatdigits

Why R format() function is not working properly to format a numeric vector?


This should be very simple. This vector:

test = c(0.027, 0.01872169, 0.1869244, 0.6997091, 0.06764486, 0.1436803, 
0.001610974, 0.5461064, 0.3066009, 0.002001355, 0.03864836, 0.391397, 
0.5145854, 0.05524137, 0.01838195, 0.02019719, 0.346739, 0.5876818, 
0.02694247, 8.277247e-05, 0.1929826, 0.7863224, 0.02061222)

class(test)
[1] "numeric"

When passed through format(test, digits = 2, scientific = FALSE) should give 2 decimals.

Instead, I have this:

 format(test, digits = 2, scientific = FALSE)
 [1] "0.027000" "0.018722" "0.186924" "0.699709" "0.067645" "0.143680" "0.001611" "0.546106" "0.306601" "0.002001" "0.038648" "0.391397" "0.514585" "0.055241" "0.018382"
[16] "0.020197" "0.346739" "0.587682" "0.026942" "0.000083" "0.192983" "0.786322" "0.020612"

No idea what is going on. I'm in Rstudio 1.4.1103 with R 4.0.3 on macOS Mojave 10.14.6. How to "force" format to just print 2 decimals instead of making sure there would be minimum 2 decimals as in "0.000083"?


Solution

  • I usually prefer sprintf for formatting numbers. Gives a lot more control.

    sprintf(test, fmt = "%0.2f")
    # [1] "0.03" "0.02" "0.19" "0.70" "0.07" "0.14" "0.00" "0.55" "0.31" "0.00" "0.04" "0.39" "0.51" "0.06" "0.02" "0.02" "0.35" "0.59"
    # [19] "0.03" "0.00" "0.19" "0.79" "0.02"