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 に答える