【问题标题】:How add 0´s in front of a number to make it 6 digits R [duplicate]如何在数字前添加 0 使其成为 6 位 R [重复]
【发布时间】:2021-12-06 14:11:29
【问题描述】:

我在其他代码语言中找到了我的问题的解决方案,但在 R 中没有。

我想在数据框中的一列中的数字前面添加 0,使其成为 6 位数字。

例如

1331
221231
21311

我想成为

001331
221231
021311

提前致谢!

【问题讨论】:

    标签: r


    【解决方案1】:

    sprintf() 是一个类似 c 格式的函数,例如

    sprintf("%06i",c(1331, 221231, 21311))
    # [1] "001331" "221231" "021311"
    

    【讨论】:

      【解决方案2】:

      这称为填充零。

      stringr 库中的函数 str_pad() 工作方式如下:

      https://www.rdocumentation.org/packages/stringr/versions/1.4.0/topics/str_pad

      df<-data.frame(zip=c(1,22,333,4444,55555))
      
      df$zip <- stringr::str_pad(df$zip, width=5, pad = "0")
      [1] "00001" "00022" "00333" "04444" "55555"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 2021-03-28
        • 1970-01-01
        • 1970-01-01
        • 2015-11-20
        • 1970-01-01
        相关资源
        最近更新 更多