2017-03-09 35 views
1

替換值的字符串值我有了像在查找列表中的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 

我不想通過硬編碼它。我想寫一個可擴展的代碼。

任何幫助,非常感謝

在此先感謝

+0

嘗試'ifelse((x < - sub('。* _','',string))%in%replacement,x,'' )' –

+0

這個代碼字對我來說,但我不能替代任何東西 grep(粘貼(替換,崩潰='|',字符串,ignore.case = TRUE)] –

+0

對不起。我將嘗試編輯問題 –

回答

0

這是我用過的另一個簡單的代碼。這不需要正則表達式函數。謝謝你的幫助

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

使用idgsub功能,然後找到id不是由is.na功能來匹配replacement長度隔離。然後用空字符''替換已識別的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" 
+0

我改變了字符串的等級,比如'string <-c('lib1_Rstudio','lib2_python','lib5_Rstudio','lib3_Jupyter','lib1_spyder','lib1_R')',並返回錯誤的結果'「Rstudio」「python」「」「Jupyter」「spyder」「R」'。你能告訴我爲什麼這是錯的嗎? –

+0

id 5大於'replacement'的長度,這是第三個元素'lib5_Rstudio'轉爲''''空字符的原因 – Sathish

+0

'replacement'的長度爲4,因爲此字符中有4個元素矢量 - '替換' – Sathish