Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Paste strings between patterns in R

I would like to paste/collapse elements of a vector together based on the index a string first appears, up until it appears again. For example,

v <- c("foo", "bar1", "bar2", "foo", "bar1", "foo", "bar1", "bar2", "bar3", "foo")
v
[1] "foo"  "bar1" "bar2" "foo"  "bar1" "foo"  "bar1" "bar2" "bar3" "foo" 

I can do this using

c(paste0(v[1:3], collapse = ""), paste0(v[4:5], collapse = ""), paste0(v[6:9], collapse = ""), paste0(v[10:10], collapse = ""))
[1] "foobar1bar2"     "foobar1"         "foobar1bar2bar3" "foo"  

The pattern is always "foo" but the number of elements after the foo always changes (like this example it’s 2, 1, 3, 0). There is a large number of lines so I’d prefer to avoid a loop. I think I could use

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

b <- which(v == "foo")
b
[1]  1  4  6 10
sapply(1:(length(b)-1), function(x) paste0(v[b[x]:(b[x+1]-1)], collapse = ""))
[1] "foobar1bar2"     "foobar1"         "foobar1bar2bar3"

I miss the last "foo". Any help would be greatly appreciated!

>Solution :

how about this

sapply(split(v, cumsum(v=='foo')), paste0, collapse='')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading