Lock the order of strings having both alphabetic and numeric components

I have string data as shown below.

a <- c("53H", "H26","14M","M47")
##"53H" "H26" "14M" "M47"

I want to correct numbers and letters in a certain order, so that numbers go first, letters go second, or vice versa. How can i do this?

##"53H" "26H" "14M" "47M"

or

##"H53" "H26" "M14" "M47"
+4
source share
3 answers

You can extract numbers and letters separately with gsub, and then use paste0 to put them in any order that you like.

a <- c("53H", "H26","14M","M47")
( nums <- gsub("[^0-9]", "", a) )    ## extract numbers
# [1] "53" "26" "14" "47"
( lets <- gsub("[^A-Z]", "", a) )    ## extract letters
# [1] "H" "H" "M" "M"

First number :

paste0(nums, lets)
# [1] "53H" "26H" "14M" "47M"

First response to letters :

paste0(lets, nums)
# [1] "H53" "H26" "M14" "M47"
+12
source

You can capture the relevant parts in groups using ()and then a backlink with gsub:

a <- c("53H", "H26","14M","M47")

gsub("^([0-9]+)([A-Z]+)$", "\\2\\1", a)
# [1] "H53" "H26" "M14" "M47"

" (^([0-9]+)). , (([A-Z]+)). . , ( \\2) , ( \\1) ).

+6

From Ananda Mahto, answer, you can order the number in first and second letters using the following code:

gsub("^([A-Z]+)([0-9]+)$", "\\2\\1", a)

because you want to grab lines that start with the letter ( ^([A-Z]+)), then grab a group of numbers ( ([0-9]+)$) /

+2
source

Source: https://habr.com/ru/post/1537386/


All Articles