2017-05-19 10 views
1

私はキーワードのテキストを検索し、見つかったキーワードを取り戻そうとしています。grepとgsubでパターンを見つけてパターンを呼び出す

text <- c("Here is some text about cats and dogs", 
      "Here is some text about turtles and chickens", 
      "Here is some text about rhinos and elephants") 
pattern <- "cat|turtle" 
HasPattern <- as.vector(NULL) 
for(i in 1:length(text)){ 
if(sum(grepl(pattern, text[i], ignore.case = TRUE)>0)) 
    HasPattern <- append(HasPattern, text[i]) 
} 

は、この出力のための所望の結果は次のようになります:

は、今私は/再現性の例でよ

gsub(grepl(pattern, text), pattern, text) # or something 
[1] cat turtle NA 

私が試してみた -

for (i in 1:length(text)){ 
    if(grepl(pattern, text[i]) == TRUE) 
    gsub(text[i], pattern, text[i]) 
} 


sub(text, pattern, text) 

gsub(grepl(pattern, text), pattern, text) 

再現可能な例: HasPatternは、私が望むものを持つベクトルを私に与えます素晴らしいです。しかし、私はまた、それらのテキストでどのようなパターンのベクトルが欲しいと思います。

答えて

2

我々はstr_extract

library(stringr) 
str_extract(text, pattern) 
#[1] "cat" "turtle" NA  
+1

優秀なあなたに感謝! str_extractは大文字と小文字を区別しますか? @MattW。 –

+0

大文字と小文字を区別しないようにパターンを変更することができます – akrun

+0

これはどのようにして通常行われますか? "Cat | cat"は私が知る唯一の方法ですが、私はパターンの大きなリストを持っています。 –

1

を使用することができますまた、

regmat <- regmatches(text,gregexpr(pattern,text)) 
regmat[lapply(regmat , length) == 0] <- NA 
unlist(regmat) 

gregexprとともに regmatchesを行うことができます出力:

> unlist(regmat) 
[1] "cat" "turtle" NA 
関連する問題