修复具有字母和数字组件的字符串的顺序(Fix the order of strings that have both letter and number components)

我有像下面的字符串数据。

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

我想按照一定顺序修复数字和字母,这样数字就会先出现,字母就会出现,或者相反。 我该怎么做?

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

要么

##"H53" "H26" "M14" "M47"

I have string data like below.

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

I want to fix the numbers and letters in a certain order such that the numbers goes first, the letters goes second, or the other way around. How can I do it?

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

or

##"H53" "H26" "M14" "M47"

最满意答案

您可以使用gsub分别提取数字和字母,然后使用paste0以任意顺序放置它们。

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"

数字第一个答案

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

信件首先回答

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

You can extract the numbers and letters separately with gsub, then use paste0 to put them in any order 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"

Numbers first answer:

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

Letters first answer:

paste0(lets, nums) # [1] "H53" "H26" "M14" "M47"修复具有字母和数字组件的字符串的顺序(Fix the order of strings that have both letter and number components)

我有像下面的字符串数据。

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

我想按照一定顺序修复数字和字母,这样数字就会先出现,字母就会出现,或者相反。 我该怎么做?

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

要么

##"H53" "H26" "M14" "M47"

I have string data like below.

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

I want to fix the numbers and letters in a certain order such that the numbers goes first, the letters goes second, or the other way around. How can I do it?

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

or

##"H53" "H26" "M14" "M47"

最满意答案

您可以使用gsub分别提取数字和字母,然后使用paste0以任意顺序放置它们。

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"

数字第一个答案

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

信件首先回答

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

You can extract the numbers and letters separately with gsub, then use paste0 to put them in any order 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"

Numbers first answer:

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

Letters first answer:

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