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 to replace and delete different underscore in a single name row

Let’s suppose I have this situation

data = data.frame('A' = c('A_A_', 'B_B_'))

A_A_ where I would like to remove the final and replace the central underscore. What can I do to save the following two steps?

data %>% 
  mutate(A = sub("_$","", A)) %>% 
  mutate(A = sub("_","->", A))

Thanks

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 :

You could use sub() with capture groups:

data$A <- sub("([^_]+)_([^_]+)_", "\\1->\\2", data$A)

The regex pattern used here says to match:

  • ([^_]+) match and capture in \1 the first term
  • _ match the first underscore
  • ([^_]+) match and capture in \2 the second term
  • _ match the final underscore

Then we splice together the two segments separated by ->.

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