2017-09-08 58 views
0

假設我有一個名爲items的數據幀,並且第一列是ItemNames。我想經過的每個項目在items$ItemNames,並檢查是否含有任何的這些話:R:想要檢查某個字符串中是否有任何元素出現在某個字符串中

words = c("apple","Apple","Pear","pear")

如果他們這樣做,字"confirmed"更換整個字符串。

我已經試過:

我用了一個for環和if語句共同做,但它失敗:

search = function(x){ 
    words = c("apple","Apple","Pear","pear") 
    for (i in length(x)){ 
     if (grepl(words, x[1][i]) == TRUE){ #where x[1][i] is the individual element in the ItemNames. 
      x[1][i] = "confirmed"} 
    } 
} 

search(items)

它沒有工作。理想情況下,如果ItemNames中包含words中的任何元素,則應將其中的所有名稱替換爲「已確認」。

+0

是你想要做精確匹配或只是部分匹配?在尋求幫助時,應該在樣本輸入和期望輸出中包含一個[可重現的示例](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。我認爲重複可以回答你的問題,但如果沒有,請編輯你的問題,使你的問題更加清晰,並且可以重新打開。 – MrFlick

回答

0

使用stringr

library(stringr) 

words <- c("apple", "Apple", "Pear", "pear") 
pattern <- paste(words, collapse = "|") 

dt <- data.frame(
    ItemNames = c("Superb apple", "Superb Pear", "Superb car"), 
    Cost = c(1, 2, 3), 
    stringsAsFactors = FALSE 
) 

index <- str_detect(dt$ItemNames, regex(pattern)) 
dt[index,]$ItemNames <- "confirmed" 
相關問題