D. Fowler
D. Fowler

Reputation: 635

add leading zeros to specific rows

I have a column that has ids with several numbers followed by a dash and additional numbers. For any id that has three digits before the dash, I want a leading 0. And, for any id that has 1 digit following the -, I want a leading zero added. Below is sample data.

id
222-5
1023-12
102-22
1231-9

I want:

id
0222-05
1023-12
0102-22
1231-09

I tried using strsplit, but was not successful. Any advice on getting this to work?

Upvotes: 1

Views: 192

Answers (1)

akrun
akrun

Reputation: 887088

We can use strsplit to split by -, then convert to numeric and use sprintf to pad the zeros at the beginning

df$id <- sapply(strsplit(df$id, "-"), function(x) 
    do.call(sprintf, c(f = "%04d-%02d", as.list(as.numeric(x)))))

df$id
#[1] "0222-05" "1023-12" "0102-22" "1231-09"

Or we can use sub to capture as groups and insert 0 when they have less number of characters

sub("-(\\d)$", "-0\\1", sub("^(\\d{3})-", "0\\1-", df$id))
#[1] "0222-05" "1023-12" "0102-22" "1231-09"

data

df <- structure(list(id = c("222-5", "1023-12", "102-22", "1231-9")), 
  class = "data.frame", row.names = c(NA, 
-4L))

Upvotes: 1

Related Questions