Pages

Friday, January 24, 2014

Add leading zeros in R

Morning coffee report...I have recently had two occasions where I needed to add leading zeros to data set.  One was working with latitude/longitude data and the second occurred when trying to plot data aggregated by zipcode.  The problem was that zipcodes that begin with zero did not contain that number and was not completely straight-forward as the number of leading zeros varied (sometime one, sometimes more than one).  After seemingly too much searching, I discovered the formatC function which accomplished exactly what I was looking for.  Below is a sample example with code that will hopefully serve as a refresher next time I need to do this.




 
Example input data without leading zeros (no zeros) and with leading zeros (leadzeros) added using the formatC function.
nozeros leadzeros
1 00001
12 00012
123 00123
1234 01234
12345 12345






No comments:

Post a Comment