0

I've used formatC to adding leading zeroes when needed but I'm currently working with census tracts that require I add trailing zeroes with no decimal. I've read through the options but can't see a way formatC places the zeroes to the end without making them decimals places? Any thoughts are much appreciated.

tract<-c(1,11,101,1001,10001,100001)
formatC(tract,width=6,format="d",flag="0") 
swhusky
  • 305
  • 3
  • 12
  • possible duplicate of [Pad with leading zeros to common width](http://stackoverflow.com/questions/14409084/pad-with-leading-zeros-to-common-width) –  Jul 21 '15 at 01:07
  • `gsub("\\s","0",formatC(tract,format="f",flag="-",digits=0,width=6))` was the best I could muster when using formatC. – thelatemail Jul 21 '15 at 01:33

2 Answers2

2

You can add trailing zeros with str_pad from the stringr package:

library(stringr)
str_pad(tract, 6, "right", "0")
# [1] "100000" "110000" "101000" "100100" "100010" "100001"
josliber
  • 43,891
  • 12
  • 98
  • 133
1

With stringi:

library(stringi)
stri_pad_right(tract, 6, "0")
zero323
  • 322,348
  • 103
  • 959
  • 935