2016-08-20 62 views
2

我試圖刪除包含特定字符模式的字符串。我的數據看起來somethink這樣的:R:如何刪除包含特定字符模式的字符串?

places <- c("copenhagen", "copenhagens", "Berlin", "Hamburg") 

我想刪除包含「哥本哈根協議」的所有元素,即"copenhagen""copenhagens"。 但我只能想出下面的代碼:

library(stringr) replacement.vector <- c("copenhagen", "copenhagens")

for(i in 1:length(replacement.vector)){ places = lapply(places, FUN=function(x) gsub(paste0("\\b",replacement.vector[i],"\\b"), "", x))

我期待FO,讓我刪除包含「哥本哈根協議」,而不必所有元素的功能指定該元素是否也包含其他字母。

最佳, 劑量

回答

3

基礎上的OP的代碼,就好像我們需要子集「的地方」。在這種情況下,它可能是更好的使用grepinvert= TRUE參數

grep("copenhagen", places, invert=TRUE, value = TRUE) 
#[1] "Berlin" "Hamburg" 

或使用grepl和否定(!

places[!grepl("copenhagen", places)] 
#[1] "Berlin" "Hamburg" 
+1

謝謝你這麼多的人! – FDose

相關問題