2017-09-08 1 views
0

items이라는 데이터 프레임이 있고 첫 번째 열이 ItemNames이라고 가정합니다.R : 특정 문자열에 단어 집합의 요소가 나타나는지 확인하고 싶습니다.

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

그들이 할 경우, 단어 "confirmed"로 전체 문자열을 대체 : 그들은 이러한 단어를 포함 할 경우 나는 items$ItemNames에서의 각 항목을 통해 가서 확인하고 싶습니다.

내가 그것을 할 수있는 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)

. 이상적으로는 words에 요소가 포함되어있는 경우 ItemNames의 모든 이름을 "확인 됨"으로 대체해야합니다.

+0

당신이 정확히 일치하거나 부분적으로 일치하는 일을하려고 있었습니까? 도움을 요청할 때 샘플 입력과 원하는 결과가있는 [reproducible example] (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" 
관련 문제