2014-10-11 38 views
11

我在R中使用grepl()來搜索下列任何一種流派是否存在於我的文本中。我現在這樣做:使用grepl搜索文本中的多個子字符串

grepl("Action", my_text) | 
grepl("Adventure", my_text) | 
grepl("Animation", my_text) |  
grepl("Biography", my_text) | 
grepl("Comedy", my_text) |  
grepl("Crime", my_text) | 
grepl("Documentary", my_text) | 
grepl("Drama", my_text) | 
grepl("Family", my_text) | 
grepl("Fantasy", my_text) | 
grepl("Film-Noir", my_text) | 
grepl("History", my_text) | 
grepl("Horror", my_text) | 
grepl("Music", my_text) | 
grepl("Musical", my_text) | 
grepl("Mystery", my_text) | 
grepl("Romance", my_text) | 
grepl("Sci-Fi", my_text) | 
grepl("Sport", my_text) | 
grepl("Thriller", my_text) | 
grepl("War", my_text) |  
grepl("Western", my_text) 

有沒有更好的方法來寫這段代碼?我可以把所有流派放在一個數組中,然後以某種方式使用grepl()

回答

19

您可以使用「或」|分隔符將流派粘貼到一起,並通過grepl作爲單個正則表達式運行。

x <- c("Action", "Adventure", "Animation", ...) 
grepl(paste(x, collapse = "|"), my_text) 

下面是一個例子。

x <- c("Action", "Adventure", "Animation") 
my_text <- c("This one has Animation.", "This has none.", "Here is Adventure.") 
grepl(paste(x, collapse = "|"), my_text) 
# [1] TRUE FALSE TRUE 
2

您可以通過列表或流派的載體,如下循環:

genres <- c("Action",...,"Western") 
sapply(genres, function(x) grepl(x, my_text)) 

要回答你的問題,如果你只是想知道結果的any元素是真的,你可以使用any()功能。

any(sapply(genres, function(x) grepl(x, my_text))) 

很簡單,如果任何元素爲TRUE,any將返回TRUE。

+0

這讓我接近我在找什麼。但我在這裏得到的是每種類型的真/假值。如果我有20個流派的數組,我會得到19個FALSE值和1個TRUE值,如果其中一個流派包含在my_text中的話。 我想從這句話中得出最終結果19 FALSE和1 TRUE在最後等於TRUE。你明白我的意思了嗎? 我該怎麼做? – user3422637 2014-10-12 01:32:47

+0

我正在做一個if語句之上,看看條件是否返回true。 – user3422637 2014-10-12 01:35:25

+0

'任何(sapply(...)' – 2014-10-12 18:56:49

相關問題