1

I have a dataframe where the have different total digits. How do I add leading zeroes when different rows need a different number of leads to achieve the max 3 digits if digits beofre decimal point less than 3.

  id    col1 
1  A       8 
2  B   125.4 
3  C    27.1 
4  E    2998
5  F   12341
6  G     7.2
7  F    6.52

Desired Output

  id    col1      col2
1  A       8       008
2  B   125.4     125.4 
3  C    27.1     027.1
4  E    2998      2998
5  F   12341     12341
6  G     7.2     007.2
7  F    6.52    006.52

I've read many solutions in Add leading zeros to numeric variable to the left of the decimal point if value is less than a specific length but have not yet solve my problem.Any help is much appreciated.

Ollie
  • 137
  • 5

2 Answers2

0

Adapting the answer to question linked to here is a way. The main problem I had was with the decimal point when there are none in the input numbers.

format_special <- function(x, leading = 3) {
  fmt <- paste0("%0", leading, "d")
  s1 <- sprintf(fmt, as.integer(sub("\\..*", "", x)))
  s2 <- sprintf("%s", sub(".*\\.{-1}", "", x))
  sprintf("%s%s%s", s1, ifelse(s2 == "", "", "."), s2)
}

format_special(df1$col1)
#> [1] "008"    "125.4"  "027.1"  "2998"   "12341"  "007.2"  "006.52"

df1$col2 <- format_special(df1$col1)
df1
#>   id     col1   col2
#> 1  A     8.00    008
#> 2  B   125.40  125.4
#> 3  C    27.10  027.1
#> 4  E  2998.00   2998
#> 5  F 12341.00  12341
#> 6  G     7.20  007.2
#> 7  F     6.52 006.52

Created on 2023-04-17 with reprex v2.0.2


Data

df1 <- " id    col1 
1  A       8 
2  B   125.4 
3  C    27.1 
4  E    2998
5  F   12341
6  G     7.2
7  F    6.52"
df1 <- read.table(text = df1, header = TRUE)

Created on 2023-04-17 with reprex v2.0.2

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
0
ifelse(nchar(sub("\\..*", "", col1)) != 3 ,
paste0(str_pad(sub("\\..*", "", col1), 3, "left", "0"), '.',sub(".*\\.", "", col1)),col1)```
Ollie
  • 137
  • 5
  • Remember that Stack Overflow isn't just intended to solve the immediate problem, but also to help future readers find solutions to similar problems, which requires understanding the underlying code. This is especially important for members of our community who are beginners, and not familiar with the syntax. Given that, **can you [edit] your answer to include an explanation of what you're doing** and why you believe it is the best approach? – Jeremy Caney Apr 18 '23 at 01:11