2016-06-14 9 views
2

これはおもちゃの例です。 a内を検索し、bに記載されている色を抽出したいと考えています。色が大文字で始まらなくても、それを抽出したいと思います。しかし、出力はaでどのように色が使われたかを教えてくれます。大文字と小文字を区別せずにRの文字列からパターンを抽出する

私が得たい回答は#"Red" NA "blueです。

a <- "She has Red hair and blue eyes" 
b <- c("Red", "Yellow", "Blue") 
str_extract(a, b)#"Red" NA NA 

私は 'stringr' からstr_extractを使用しますが、他の関数/パッケージ(例えば、grep)を使用させていただきます。

+0

すべての文字列を同じケースに変換するのが最も簡単です(tolowerまたは?toupperの関数を参照)。 – Dave2e

答えて

3

私たちは、これがbase R

unlist(sapply(tolower(b), function(x) { 
     x1 <- regmatches(a, gregexpr(x, tolower(a))) 
     replace(x1, x1 == "character(0)", NA)}), use.names=FALSE) 
# "Red"  NA "blue" 

や@ leerssejの回答などからインスピレーション

library(stringr) 
str_extract(a, fixed(b, ignore_case=TRUE)) 
#[1] "Red" NA  "blue" 
+0

私が間違っていない限り、あなたのソリューションは私の最初の試みと同じ問題を抱えています... OPは大文字を 'a'から保つことを望んでいます –

+1

@DominicComtoisここでも修正されました! – akrun

3

stringrがakrunの答えに改良としてignore.case()機能

str_extract(a, ignore.case(b))#"Red" NA  "blue" 
+0

ありがとうございます。これにより、エラーメッセージが表示されます。ignore.case(x)ではなく、(fixed | coll | regexp)(x、ignore_case = TRUE)を使用してください。そう;多分私はこれを行う必要があります:str_extract(固定、(ignore_case =真)、固定(b、ignore_case =真))? – milan

+2

@milanこれはエラーではありません。それは単なるメッセージであり、警告でもありません。コードは正しい結果を提供します。しかし、例えば 'str_extract(a、(固定)(b、ignore_case = TRUE))'を使うことができます。 – RHertel

+0

私が見たように、私の最後のコメントの提案はすでに@ akrunの編集に含まれていました。 – RHertel

2

を持って行うことができます、あなたは変更を使用することができますo Fマッチングのためのケースが、それでも要素に彼らがもともとaで書かれている方法を返す:小文字を区別しない場合に使用することができますstringi 1で

positions <- str_locate(toupper(a), toupper(b)) 
words <- apply(positions, 1, function(x) substr(a,x[1],x[2])) 
words[!is.na(words)] 

## [1] "Red" "blue" 
+1

これで修正されました! –

3

library(stringr) 
a <- "She has Red hair and blue eyes" 
b <- c("Red", "Yellow", "Blue") 

positions <- str_locate(toupper(a), toupper(b)) 
apply(positions, 1, function(x) substr(a,x[1],x[2])) 

## [1] "Red" NA "blue" 

かを、NAを排除するために...オプション

library(stringi) 
stri_extract_all_fixed(a, b, opts_fixed = list(case_insensitive = TRUE)) 
#[[1]] 
#[1] "Red" 
#[[2]] 
#[1] NA 
#[[3]] 
#[1] "blue" 


# or using simplify = TRUE to get a non-list output 
stri_extract_all_fixed(a, b, opts_fixed = list(case_insensitive = TRUE), 
    simplify = TRUE) 
#  [,1] 
#[1,] "Red" 
#[2,] NA  
#[3,] "blue" 
関連する問題