Adding conditional leading or trailing zeros

4.9k Views Asked by At

I need help conditionally adding leading or trailing zeros.

I have a dataframe with one column containing icd9 diagnoses. as a vector, the column looks like:

"33.27" "38.45" "9.25" "4.15" "38.45" "39.9" "84.1" "41.5" "50.3" 

I need all the values to have the length of 5, including the period in the middle (not counting ""). If the value has one digit before the period, it need to have a leading zero. If value has one digit after the period, it need to have zero at the end. So the result should look like this:

"33.27" "38.45" "09.25" "04.15" "38.45" "39.90" "84.10" "41.50" "50.30" 

Here is the vector for R:

icd9 <- c("33.27", "38.45", "9.25", "4.15", "38.45", "39.9", "84.1", "41.5", "50.3" )
4

There are 4 best solutions below

0
On

You can also use sprintf after converting the vector into numeric.

sprintf("%05.2f", as.numeric(icd9))
[1] "33.27" "38.45" "09.25" "04.15" "38.45" "39.90" "84.10" "41.50" "50.30"

Notes

  • The examples in ?sprint to get work out the proper format.
  • There is some risk of introducing errors due to numerical precision here, though it works well in the example.
1
On

Using this function called change that accepts the argument of the max number of characters, i think it can help

 change<-function(x, n=max(nchar(x))) gsub(" ", "0", formatC(x, width=n))
    icd92<-gsub(" ","",paste(change(icd9,5)))
1
On

This does it in one line

formatC(as.numeric(icd9),width=5,format='f',digits=2,flag='0')

0
On

ICD-9 codes have some formatting quirks which can lead to misinterpretation with simple string processing. The icd package on CRAN takes care of all the corner cases when doing ICD processing, and has been battle-tested over about six years of use by many R users.