我在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)
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来编写这段代码?我可以将所有类型放在一个数组中,然后以某种方式使用grepl()
它吗?
Ric*_*ven 30
您可以将类型与"或" |
分隔符粘贴在一起,并将其grepl
作为单个正则表达式运行.
x <- c("Action", "Adventure", "Animation", ...)
grepl(paste(x, collapse = "|"), my_text)
Run Code Online (Sandbox Code Playgroud)
这是一个例子.
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
Run Code Online (Sandbox Code Playgroud)