我有一个带小数点的数字向量。我想在数字前面添加一个0,在小数位前只有一个整数,同时在有一个的值中保留尾随0。例如,5.466
应为05.466
,43.770
应为43.770
。
这是数据
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)
我试过了
longM2<-formatC(longM,flag=0, width=6,drop0trailing=F)
和
library(stringr)
longM22<-str_pad(longM,width=6,side="both",pad="0")
答案 0 :(得分:5)
您可以使用sprintf
:
sprintf("%06.3f",longM)
e.g。
> sprintf("%06.3f",c(1.0, 33.4, 12.345,0.1243,12000))
[1] "01.000" "33.400" "12.345" "00.124" "12000.000"
格式%06.3f
表示:
(*)请注意,如果数字为>= 100
,则无论如何都会在该点之前显示超过2位数(基本上打破了格式约束)。