Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add leading zeros within string

Tags:

regex

r

I have a series of column names that I'm trying to standardize.

names <- c("apple", "banana", "orange", "apple1", "apple2", "apple10", "apple11", "banana2", "banana12")

I would like anything that has a one digit number to be padded by a zero, so

apple
banana
orange
apple01
apple02
apple10
apple11
banana02
...

I've been trying to use stringr

strdouble <- str_detect(names, "[0-9]{2}")
strsingle <- str_detect(names, "[0-9]")

str_detect(names[strsingle & !strdouble])

but unable to figure out how to selectively replace/prepend...

like image 932
ano Avatar asked Dec 01 '15 17:12

ano


People also ask

How to add leading zeros before text strings in Excel?

The easiest way to put leading zeros before text strings in Excel is using the RIGHT function: "0000" is the maximum number of zeros you want to add. For example, to add 2 zeros, you type "00". Cell is a reference to the cell containing the original value. String_length is how many characters the resulting string should contain.

How do you add leading zeros to a 5 digit number?

For example, to add leading zeros to create a 5-digit number, use the following format code: 00000. By using Excel custom numbers formats, you can add leading zeros to create fixed-length numbers, like in the above example, and variable-length numbers.

How to add leading zeros to strings in pandas Dataframe?

You can use the following syntax to add leading zeros to strings in a pandas DataFrame: This particular formula adds as many leading zeros as necessary to the strings in the column titled ‘ID’ until each string has a length of 7. Feel free to replace the 7 with another value to add a different number of leading zeros.

How many zeros can you add to a column in Excel?

As shown in the screenshot below, the formula adds just one leading zero to all cells in a column regardless of how many characters the original value contains: In the same manner, you can insert 2 leading zeros (00), 3 zeros (000) or as many zeros as you want before numbers and text strings.


1 Answers

You can use sub("([a-z])([0-9])$","\\10\\2",names) :

[1] "apple"    "banana"   "orange"   "apple01"  "apple02"  "apple10"  "apple11"  "banana02"
[9] "banana12"

It only changes the names where there is a single digit following a letter (the $ is the end of the string).

The \\1 selects the first block in () : the letter. Then it puts a leading 0, then the second block in () : the digit.

like image 60
etienne Avatar answered Sep 27 '22 00:09

etienne