We have answer of your question!

100% solved queries, no empty question

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


0

Advertisement


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?

Question author Jmm | Source

Answer


1


Advertisement


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

Advertisement


Tickanswer.com is providing the only single recommended solution of the question R: How to split string and keep part of it? under the categories i.e r , split , . Our team of experts filter the best solution for you.

Related Search Queries:

You may also add your answer!