用前导零创建数字序列

时间:2016-11-17 15:01:07

标签: r

此问题之前已使用Console.writelines函数解决,但在我的R版本中无法使用,我无法找到它所属的软件包。

我只是想创建一个0-99的数字序列,其中前导零的格式为“xxx”,所以我的数字应该是000,001,002 ... 099。

当我使用时:

seq(000:099)

R返回1,2,3等。

有一种简单的方法吗?我觉得它应该比它容易得多。

这与以前的答案不同,因为我需要在数字0-9前面加两个零,在数字10-99前面只需要1个零,而前一个问题只是在所有数字前面要求1个零。

1 个答案:

答案 0 :(得分:6)

例如1:100,前导零总数最多为三位数:

sprintf('%0.3d', 1:100)
  [1] "001" "002" "003" "004" "005" "006" "007" "008" "009" "010" "011" "012"
 [13] "013" "014" "015" "016" "017" "018" "019" "020" "021" "022" "023" "024"
 [25] "025" "026" "027" "028" "029" "030" "031" "032" "033" "034" "035" "036"
 [37] "037" "038" "039" "040" "041" "042" "043" "044" "045" "046" "047" "048"
 [49] "049" "050" "051" "052" "053" "054" "055" "056" "057" "058" "059" "060"
 [61] "061" "062" "063" "064" "065" "066" "067" "068" "069" "070" "071" "072"
 [73] "073" "074" "075" "076" "077" "078" "079" "080" "081" "082" "083" "084"
 [85] "085" "086" "087" "088" "089" "090" "091" "092" "093" "094" "095" "096"
 [97] "097" "098" "099" "100"