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

Search strings in dataframe for specific pattern and update with another column

I have the following toy dataframe:

ID <- c(15, 25, 90, 1, 23, 543)

HTML <- c("[demography_form][1]<div></table<text-align>[demography_form_date][1]", "<text-ali>[geography_form][1]<div></table<text-align>[geography_form_date][1]", "[social_isolation][1]<div></table<div><text-align>[social_isolation_date][1]", "<text-align>[geography_form][1]<div></table<text-align>[geography_form_date][1]", "<div>[demography_form][1]<div></table<text-align>[demography_form_date][1]", "[geography_form][1]<div></table<text-align>[geography_form_date][1]</table")

df <- data.frame(ID, HTML)

enter image description here

How can I search each string in the HTML column for occrrances of the integer surrounded by square brackets, replacing that value with the integer in the adjacent ID column? If there is no square brackets with an integer in the row I would like no operation to occur. 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 :

Use str_replace to replace only the first occurrence.

library(stringr)

df$HTML <- str_replace_all(df$HTML, "\\[\\d\\]", str_c("[", df$ID, "]"))

Or using dplyr

library(dplyr)

df <- df %>% 
  mutate(HTML = str_replace_all(HTML, "\\[\\d\\]", str_c("[", ID, "]")))
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