R:如何分割字符串并保存它的一部分?

时间:2021-03-15 21:40:08

I have a lot of strings like shown below.

我有很多字符串,如下所示。

> x=c("cat_1_2_3", "dog_2_6_3", "cow_2_8_6")
> x
[1] "cat_1_2_3" "dog_2_6_3" "cow_2_8_6"

I would like to seperate the string, while still holding the first part of it, as demonstrated below.

我想要分离字符串,同时仍然保留第一部分,如下所示。

"cat_1" "cat_2" "cat_3" "dog_2" "dog_6" "dog_3" "cow_2" "cow_8" "cow_6"

Any suggestions?

有什么建议吗?

2 个解决方案

#1


2  

We can use sub

我们可以使用子

scan(text=sub("([a-z]+)_(\\d+)_(\\d+)_(\\d+)", "\\1_\\2,\\1_\\3,\\1_\\4",
          x), what ='', sep=",", quiet = TRUE)
#[1] "cat_1" "cat_2" "cat_3" "dog_2" "dog_6" "dog_3" "cow_2" "cow_8" "cow_6"

Or another option is split the string with

或者另一个选项是分割字符串

unlist(lapply(strsplit(x, "_"), function(x) paste(x[1], x[-1], sep="_")))

#2


1  

You could try to split the string, then re-combine using paste.

您可以尝试分割字符串,然后使用粘贴重新组合。

f <- function(x) {
    res <- strsplit(x,'_')[[1]]
    paste(res[1], res[2:4], sep='_')
}

x <- c("cat_1_2_3", "dog_2_6_3", "cow_2_8_6")

unlist(lapply(x, f))

#1


2  

We can use sub

我们可以使用子

scan(text=sub("([a-z]+)_(\\d+)_(\\d+)_(\\d+)", "\\1_\\2,\\1_\\3,\\1_\\4",
          x), what ='', sep=",", quiet = TRUE)
#[1] "cat_1" "cat_2" "cat_3" "dog_2" "dog_6" "dog_3" "cow_2" "cow_8" "cow_6"

Or another option is split the string with

或者另一个选项是分割字符串

unlist(lapply(strsplit(x, "_"), function(x) paste(x[1], x[-1], sep="_")))

#2


1  

You could try to split the string, then re-combine using paste.

您可以尝试分割字符串,然后使用粘贴重新组合。

f <- function(x) {
    res <- strsplit(x,'_')[[1]]
    paste(res[1], res[2:4], sep='_')
}

x <- c("cat_1_2_3", "dog_2_6_3", "cow_2_8_6")

unlist(lapply(x, f))