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

How can I concatinate strings that have a specific pattern with the previous string in character vector?

I have a character vector listed below.

vec <- c(
  'red yellow orange', 'green white', 'blue', 'orange purple', 'green brown', 'red'
)

I would like to paste blue and red in front of the string that precedes them. Here is my expected output.

[1] "red yellow orange" "blue green white" "blue" "orange purple"  "red green brown"  "red" 

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

>Solution :

with ifelse and head_tail

c(ifelse(
   grepl("^red|blue$", tail(vec,-1)), 
   paste(tail(vec,-1), head(vec,-1)), 
   head(vec, -1)), tail(vec,1))
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