Fisseha Berhane
Fisseha Berhane

Reputation: 2653

Replace string in one column by another column

I have a dataframe that has two columns and I want to replace some string from the first column by the second column. In the dataframe below, I want the 'em' tag to be replaced by 'a' tag with the url on the ulrs column.

df1 = data.frame(text = c("I like <em'>Rstudio</em> very much", 
                      "<em'> Anaconda</em> is an amazing data science tool"), 
urls = c('https://www.rstudio.com/', 'https://anaconda.org/'))

I am looking for a vector like below.

text = c("I like <a href = 'https://www.rstudio.com/'>Rstudio</a> very much", 
        "<a href = 'https://anaconda.org/'> Anaconda</a> is an amazing data science tool")

Upvotes: 0

Views: 734

Answers (1)

MKR
MKR

Reputation: 20085

An option using gsub and mapply can be as:

mapply(function(x,y)gsub("<em'>.*</em>",x,y),df1$urls, df1$text)

# [1] "I like https://www.rstudio.com/ very much"            
# [2] "https://anaconda.org/ is an amazing data science tool"

Data:

df1 = data.frame(text = c("I like <em'>Rstudio</em> very much", 
                          "<em'> Anaconda</em> is an amazing data science tool"), 
                 urls = c('https://www.rstudio.com/', 'https://anaconda.org/'))

Upvotes: 1

Related Questions