Adding 0 as a complement to numbers with decimal points in R

I have a vector of numbers with decimal point. I would like to add 0 in front of numbers with one integer to the decimal place, while keeping the trailing 0 in values ​​that have one. For example, 5.466

must read 05.466

and 43.770

must read 43.770

.

Here is the data

longM<-c(18.846, 18.906, 5.466, 11.19, 6.894, 7.578, 5.13, 53.868, 57.216, 
0.228, 41.892, 57.576, 44.19, 29.292, 16.452, 48.306, 16.224, 
28.566, 32.328, 25.908, 9.318, 7.332, 38.838, 4.812, 27.588, 
20.922, 30.804, 43.872, 7.734, 41.856, 3.222, 47.364, 5.754, 
21.792, 43.494, 50.82, 48.618, 4.524, 5.454, 48.744, 36.504, 
44.328, 38.61, 39.084, 38.52, 39.504, 4.206, 47.928, 15.996, 
42.99, 46.116, 26.496, 44.148, 40.284, 43.296, 34.248, 22.242, 
29.838, 31.38, 27.12, 22.278, 21.36, 20.142, 15.93, 54.726, 12.072, 
13.05, 11.886, 1.242, 54.42, 48.132, 42.954, 4.986, 32.604, 12.018, 
43.77, 26.172, 30.27, 39.738, 47.514, 27.012, 45.654, 35.796, 
44.52, 30.564)

      

I tried

longM2<-formatC(longM,flag=0, width=6,drop0trailing=F)

      

and

library(stringr)
 longM22<-str_pad(longM,width=6,side="both",pad="0")

      

+3


source to share


1 answer


You can use sprintf

:

sprintf("%06.3f",longM)

      

eg.

> sprintf("%06.3f",c(1.0, 33.4, 12.345,0.1243,12000))
[1] "01.000"    "33.400"    "12.345"    "00.124"    "12000.000"

      



Format %06.3f

means:

  • you want to use the number using zeros
  • you want to format the number using exactly 6 characters (*)
  • you need 3 digits precision after the dot

(*) Note that if a number >= 100

, more than two digits will be displayed anyway (mostly violating the format constraint).

+5


source







All Articles