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)
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.
>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, "]")))
