如何添加前导零?

如何添加前导零?

我有一组数据如下所示:


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.0,1.8,1.4)

data <- data.frame(anim,sex,wt)


data

   anim sex  wt anim2

1 25499   1 0.8     2

2 25500   2 1.2     2

3 25501   2 1.0     2

4 25502   1 2.0     2

5 25503   2 1.8     2

6 25504   1 1.4     2

我希望在每个动物身份之前加一个零:


data

   anim sex  wt anim2

1 025499   1 0.8     2

2 025500   2 1.2     2

3 025501   2 1.0     2

4 025502   1 2.0     2

5 025503   2 1.8     2

6 025504   1 1.4     2

为了利息起见,如果我需要在动物身份之前加两个或三个零呢?


慕运维8079593
浏览 827回答 4
4回答

德玛西亚99

中有多少位数的通用解决方案。data$anim,使用sprintf功能。它的工作方式如下:sprintf("%04d",&nbsp;1)#&nbsp;[1]&nbsp;"0001"sprintf("%04d",&nbsp;104)#&nbsp;[1]&nbsp;"0104"sprintf("%010d",&nbsp;104)#&nbsp;[1]&nbsp;"0000000104"就你而言,你可能想:data$anim <- sprintf("%06d", data$anim)

呼啦一阵风

在@Goodside‘srepsonse上扩展:在某些情况下,您可能希望使用零填充字符串(例如,FIPS代码或其他类似数字的因素)。在OSX/Linux中:>&nbsp;sprintf("%05s",&nbsp;"104")[1]&nbsp;"00104"但因为sprintf()调用OS的Csprintf()命令,讨论这里,在Windows 7中,您会得到一个不同的结果:>&nbsp;sprintf("%05s",&nbsp;"104")[1]&nbsp;"&nbsp;&nbsp;104"所以在Windows机器上的工作是:>&nbsp;sprintf("%05d",&nbsp;as.numeric("104"))[1]&nbsp;"00104"

慕妹3242003

str_pad从stringr包裹是另一种选择。anim&nbsp;=&nbsp;25499:25504str_pad(anim,&nbsp;width=6,&nbsp;pad="0")
打开App,查看更多内容
随时随地看视频慕课网APP