JMM
JMM

Reputation: 53

R: How to split string and keep part of it?

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?

Upvotes: 3

Views: 986

Answers (2)

mpjdem
mpjdem

Reputation: 1544

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))

Upvotes: 2

akrun
akrun

Reputation: 886968

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="_")))

Upvotes: 2

Related Questions