How to add leading zeros?

后端 未结 8 1892
一生所求
一生所求 2020-11-21 05:23

I have a set of data which looks something like this:

anim <- c(25499,25500,25501,25502,25503,25504)
sex  <- c(1,2,2,1,2,1)
wt   <- c(0.8,1.2,1.0,2.         


        
8条回答
  •  别跟我提以往
    2020-11-21 05:38

    For a general solution that works regardless of how many digits are in data$anim, use the sprintf function. It works like this:

    sprintf("%04d", 1)
    # [1] "0001"
    sprintf("%04d", 104)
    # [1] "0104"
    sprintf("%010d", 104)
    # [1] "0000000104"
    

    In your case, you probably want: data$anim <- sprintf("%06d", data$anim)

提交回复
热议问题