Reputation: 1
I have a dataset that has column wells A1-A24, B1-B24 all through P24. I would like to add a 0 to the middle of any wells with only 2 characters. For example, A1 would become A01 and B24 would stay B24.
This is an example of what I have:
data.frame
1 A1
2 A2
3 A3
4 A4
5 A5
6 A6
7 A7
8 A8
9 A9
10 A10
11 A11
12 A12
This is what I want:
data.frame
1 A01
2 A02
3 A03
4 A04
5 A05
6 A06
7 A07
8 A08
9 A09
10 A10
11 A11
12 A12
Upvotes: 0
Views: 171
Reputation: 102609
We can do like this with gsub
+ sprintf
transform(
df,
y = sprintf("%s%02i", gsub("\\d", "", y), as.numeric(gsub("\\D", "", y)))
)
which gives
x y
1 1 A01
2 2 A02
3 3 A03
4 4 A04
5 5 A05
6 6 A06
7 7 A07
8 8 A08
9 9 A09
10 10 A10
11 11 A11
12 12 A12
> dput(df)
structure(list(x = 1:12, y = c("A1", "A2", "A3", "A4", "A5",
"A6", "A7", "A8", "A9", "A10", "A11", "A12")), class = "data.frame", row.names = c(NA,
-12L))
Upvotes: 1