14

我在 R 中使用 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()吗?

4

2 回答 2

37

您可以将流派与“或”|分隔符粘贴在一起,并将其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
于 2014-10-11T22:08:57.733 回答
3

您可以循环浏览流派列表或向量,如下所示:

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

要回答您的问题,如果您只想知道any结果的元素是否为 TRUE,您可以使用该any()函数。

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

很简单,如果 的任何元素为 TRUE,any则返回 TRUE。

于 2014-10-11T21:48:49.450 回答