1

I have census tract data, and I want to add leading zeros if the value is less than 6 digits, including the two zeroes that come after the decimal point. I tried using str_pad, but that adds zeroes to the observations that already have 6 digits (and gets rid of the .00).

I think what's happening is that it's not counting the "00" after the decimal point as digits. How do I make sure that the zeroes after the decimal point are being counted?

Data:

31         9806.00
32         9808.00
33         9806.00
34          201.00
35          201.00
36          206.00
37          209.00
38          201.00
39          201.00
40          209.00

How I want it to look:

31         9806.00
32         9808.00
33         9806.00
34         0201.00
35         0201.00
36         0206.00
37         0209.00
38         0201.00
39         0201.00
40         0209.00
user12310746
  • 279
  • 1
  • 10

2 Answers2

3

You can use sprintf :

sprintf('%04s.%s', sub('\\..*', '', df$V2), sub('.*\\.', '', df$V2))
#[1] "9806.00" "9808.00" "9806.00" "0201.00" "0201.00" "0206.00" 
#    "0209.00" "0201.00" "0201.00" "0209.00"

We can extract the integer part and decimal part of the number separately with sub. Make the integer part of specific width (4) and paste it with decimal part.

data

df <- structure(list(V1 = c("31", "32", "33", "34", "35", "36", "37", 
"38", "39", "40"), V2 = c("9806.00", "9808.00", "9806.00", "201.00", 
"201.00", "206.00", "209.00", "201.00", "201.00", "209.00")), 
class = "data.frame", row.names = c(NA, -10L))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0
y= c(9808.00,  9806.00, 9806.00,  201.00,  201.00, 206.00, 201.00, 201.00, 201.00)

nchar(y)

ifelse(nchar(y)== 2, paste(y, ".00", sep=""), paste("00",y,".00", sep=""))

If you want to conserve the left "00", you would work with string format!! Also, it is a "non elegant" way. If your data are more complex (ie 201.02 or 3.00), then this solution would not work, but there are several ways to solve it