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 add "swab" to text string when "dry0" occurs in R

I have a column with swab IDs. The normal ID nomenclature is "dryswab00001". However there are some samples as "dry00135". How would I str_detect those IDs and insert "swab" before the leading zero/number?

Data


data <- structure(list(swab_id = c("dryswab00001", "dry00002")), class = "data.frame", row.names = c(NA, 
-2L))

>Solution :

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

You can use str_detect and str_replace in stringr to do this:

install.packages("stringr")
library("stringr")

# Use str_detect to identify IDs that need modification
update <- str_detect(data$swab_id, "^dry\\d+")

# Modify the IDs
data$swab_id[update] <- str_replace(data$swab_id[update], "^dry", "dryswab")

Final dataframe:
swab_id
1 dryswab00001
2 dryswab00002

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