将字符串值替换为 R 中查找列表中的值

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

我有一个数据集,其中有一列像

   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')

我想替换与替换值匹配的字符串值 ID。我现在正在使用以下代码

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

这是我用来查找案例的另一段代码

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

我想更新我找到的那些 我希望输出像

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

我不想通过硬编码来做到这一点。我想编写可扩展的代码。

非常感谢任何帮助

提前致谢

使用gsub函数隔离id,然后通过is.na函数找到与replacement长度不匹配的id。然后将识别出的id替换为空字符''.

编辑: 由于您更改了问题中的字符串数据,因此我修改了 gsub 函数。 gsub 函数中使用的模式将查找紧跟在 lib 文本之后的数值,并忽略字符串元素的剩余部分。

replacement<-c('Rstudio','Jupyter','spyder','R')

string<-c('lib1_Rstudio','lib2_Rstudio','lib5_python','lib3_Jupyter','lib1_spyder','lib1_R')
index <- is.na( replacement[ as.integer( gsub( "lib([[:digit:]])*[[:alnum:]_\ ]*", "\1", string)) ] )
a1 <- sapply( strsplit(string, "_"), function( x ) x[2] )
a1[ index ] <- ''
a1
# [1] "Rstudio" "Rstudio" ""        "Jupyter" "spyder"  "R"    

string <- c('lib1_Rstudio_case1','lib2_Rstudio_case1and2','lib5_python_notthe correct_language','lib3_Jupyter_really_good','lib1_spyder_nice','lib1_R_the_core')
index <- is.na( replacement[ as.integer( gsub( "lib([[:digit:]])*[[:alnum:]_\ ]*", "\1", string)) ] )
a1 <- sapply( strsplit(string, "_"), function( x ) x[2] )
a1[ index ] <- ''
a1
# [1] "Rstudio" "Rstudio" ""        "Jupyter" "spyder"  "R"

这是我使用的另一个简单代码。这不需要正则表达式 function.Thanks 的帮助

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)]=''