簡體   English   中英

將字符串值替換為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"

這是我使用的另一個簡單代碼。 不需要regex函數。謝謝您的幫助

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM