您可以使用words
and df$text
直接进入grep
找到要设置为 1 的行。
df$transport[grep(words, df$text)] <- 1
另一种方法是使用grepl
并使用+
to get 0
and 1
:
+grepl(words, df$text)
#[1] 1 0 1 0 0 0
如果只需要匹配整个单词,则需要将它们包围起来\b
来匹配边界。
+grepl(paste0("\\b(", words, ")\\b"), df$text)
#[1] 1 0 1 0 0 0
基准:
bench::mark(
grepl = +grepl(words, df$text)
, "grepl\\b" = +grepl(paste0("\\b(", words, ")\\b"), df$text)
, greplPerl = +grepl(words, df$text, perl = TRUE)
, stringr = +stringr::str_detect(df$text, words)
, stringi = +stringi::stri_detect_regex(df$text, words)
, like = +data.table::like(df$text, words)
)
# expression min median `itr/sec` mem_alloc `gc/sec` n_itr n_gc total_time
# <bch:expr> <bch:t> <bch:t> <dbl> <bch:byt> <dbl> <int> <dbl> <bch:tm>
#1 grepl 10.61µs 11.61µs 62577. 0B 6.26 9999 1 159.8ms
#2 grepl\b 15.29µs 16.31µs 59343. 0B 11.9 9998 2 168.5ms
#3 greplPerl 5.5µs 5.9µs 164148. 0B 0 10000 0 60.9ms
#4 stringr 10.01µs 10.78µs 88661. 0B 17.7 9998 2 112.8ms
#5 stringi 7.48µs 7.93µs 123578. 0B 12.4 9999 1 80.9ms
#6 like 11.83µs 12.66µs 77189. 0B 7.72 9999 1 129.5ms
在这种情况下使用grepl
from base设置时perl = TRUE
是最快的方法。