rreplacegsubqdap

Replace the string value with value in the find list in R


I have a dataset that has a column like

   string<-c('lib1_Rstudio_case1','lib2_Rstudio_case1and2','lib5_python_notthe correct_language','lib3_Jupyter_really_good','lib1_spyder_nice','lib1_R_the_core')
   replacement<-c('Rstudio','Jupyter','spyder','R')

I want to replace the string value id they match the value in replacement. I am using the following code right now

gsub(paste(replacement, collapse = "|"), replacement = replacement, x = string)

This in another piece of code which i am using to find the cases

string[grepl(paste(replacement, collapse='|'), string, ignore.case=TRUE)]

I want to update the ones that I find I want the output to be like

Rstudio,Rstudio,'',Jupyter,spyder,R

I don't want to do it by hard coding it. I want to write a code that is scalable.

Any help is really appreciated

thanks in advance


Solution

  • This another simple code I used. That doesn't need the regex function.Thanks for the help

    string<-c('lib1_Rstudio_case1','lib2_Rstudio_case1and2','lib5_python_notthe correct_language','lib3_Jupyter_really_good','lib1_spyder_nice','lib1_R_the_core')
    replacement<-c('R','Jupyter','spyder','Rstudio')
    replaced=string
    replaced=''
    
    
    for (i in 1:length(replacement))
    {
      replaced[which(grepl(replacement[i],string))]=replacement[i]
    }
    replaced[is.na(replaced)]=''