llb1706
llb1706

Reputation: 45

How do I add characters on specific strings?

I'm kind of new to R and this has been bugging me.

I have a column like this:

2009m1

2009m2

2009m3

...

2009m12

How do I add zeros on months that have only 1 digit? I want something like this:

2009m01

2009m02

2009m03

...

2009m12

Thanks!

Upvotes: 2

Views: 42

Answers (1)

akrun
akrun

Reputation: 887028

Here is an option with sub where we match the 'm' followed by a digit (\\d - captured as a group (...)) at the end ($) of the string and replace with 'm' '0' and the backreference (\\1) of the captured group

df1$col1 <- sub("m(\\d)$", "m0\\1", df1$col1)
df1$col1
#[1] "2009m01" "2009m02" "2009m03" "2009m04" "2009m05" "2009m06" "2009m07" "2009m08" "2009m09" "2009m10" "2009m11"
#[12] "2009m12"

Or another option is gsubfn with sprintf

library(gsubfn)
gsubfn("\\d+$", ~ sprintf('%02d', as.numeric(x)), df1$col1)

data

df1 <- data.frame(col1 = paste0(2009, 'm', 1:12), stringsAsFactors = FALSE)

Upvotes: 2

Related Questions