2014-10-11 77 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

相关问题