1

I have several IDs I am working with. I want to add a leading zero for values that have 1 integer after the dash in id. Here is sample data. I

id
2034-5
1023-12
1042-22
1231-9

I want this:

id
2034-05
1023-12
1042-22
1231-09

I tried this, but it's not working. Any advice?

x <-sprintf("%02d", df$id)
D. Fowler
  • 601
  • 3
  • 7

3 Answers3

2

You could actually use sub here for a base R option:

df$id <- sub("-(\\d)$", "-0\\1", df$id)
df

       id
1 2034-05
2 1023-12
3 1042-22
4 1231-09

Data:

df <- data.frame(id=c("2034-5", "1023-12", "1042-22", "1231-9"), stringsAsFactors=FALSE)
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

To use sprintf you have to separate out both the numbers, use sprintf on second number and then combine them again.

library(dplyr)
library(tidyr)

df %>%
  separate(id, c('id1', 'id2')) %>%
  mutate(id2 = sprintf('%02s', id2)) %>%
  unite(id, id1, id2, sep = '-')

#       id
#1 2034-05
#2 1023-12
#3 1042-22
#4 1231-09
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
0

An option with strsplit and sprintf from base R

df$id <-  sapply(strsplit(df$id, "-"), function(x) 
        do.call(sprintf, c(as.list(x), fmt = "%s-%02s")))
df$id
#[1] "2034-05" "1023-12" "1042-22" "1231-09"
akrun
  • 874,273
  • 37
  • 540
  • 662