D. Fowler
D. Fowler

Reputation: 635

add numbers to specific observations

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)

Upvotes: 1

Views: 37

Answers (3)

akrun
akrun

Reputation: 887901

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"

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 389275

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

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522731

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)

Upvotes: 2

Related Questions