1

How to convert "A01" to "A1" using R?

As the first step I tried to get the middle character in the string but I couldn't.

STR <- "A01"
p <- as.character(substr(STR,2,1))

I get the following for p. I am very new to R. Please advice me.

[1] ""
RanonKahn
  • 853
  • 10
  • 34

2 Answers2

4

You can use lookaround to replace 0 values:

sub('(?<![0-9])0*(?=[0-9])', '', STR, perl=TRUE)
[1] "A1"

The expression matches all 0 characters that are not preceded by a number, but are followed by a number.

sub('(?<![0-9])0*(?=[0-9])', '', 'A0010', perl=TRUE)
[1] "A10"

sub('(?<![0-9])0*(?=[0-9])', '', 'A00', perl=TRUE)
[1] "A0"
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
4

We can also do this without regex lookarounds

sub("([A-Z]+)0*([0-9]+)", "\\1\\2", c("A01", "A0010", "A00"))
#[1] "A1"  "A10" "A0" 
akrun
  • 874,273
  • 37
  • 540
  • 662