R - Grepl 向量过向量

R - Grepl vector over vector

我有一个字符串向量 (v1),如下所示:

> head(v1)
[1] "do_i_need_to_even_say_it_do_i_well_here_i_go_anyways_chris_cornell_in_chicago_tonight"                                       
[2] "going_to_see_harry_sunday_happiness"                                                                                         
[3] "this_motha_fucka_stay_solid_foh_with_your_naieve_ass_mentality_your_synapsis_are_lacking_read_a_fucking_book_for_christ_sake"
[4] "why_twitter_will_soon_become_obsolete_http_www.imediaconnection.com_content_23465_asp"                                       
[5] "like_i_said_my_back_still_fucking_hurts_and_im_going_to_complain_about_it_like_no_ones_business_http_tumblr.com_x6n25amd5"   
[6] "my_picture_with_kris_karmada_is_gone_forever_its_not_in_my_comments_on_my_mysapce_or_on_my_http_tumblr.com_xzg1wy4jj"

另一个字符串向量 (v2) 如下所示:

> head(v2)
[1] "here_i_go" "going" "naieve_ass" "your_synapsis"   "my_picture_with"   "roll" 

最快的方法是什么 return 一个向量列表,其中每个列表项代表 v1 中的每个向量项,每个向量项都是正则表达式匹配项 [= =14=] 出现在那个 v1 项目中,像这样:

[[1]]
[1] "here_i_go"

[[2]]
[1] "going"

[[3]]
[1] "naieve_ass"      "your_synapsis"

[[4]]

[[5]]
[1] "going"

[[6]]
[1] "my_picture_with"

如果你想要速度,我会使用 stringi。你似乎没有任何正则表达式,只有固定模式,所以我们可以使用 fixed stri_extract,并且(因为你没有提到如何处理多个匹配项)我只假设提取第一个匹配项很好,使用 stri_extract_first_fixed.

可以加快我们的速度

可能不值得对这么小的示例进行基准测试,但这应该相当快。

library(stringi)
matches = lapply(v1, stri_extract_first_fixed, v2)
lapply(matches, function(x) x[!is.na(x)])
# [[1]]
# [1] "here_i_go"
# 
# [[2]]
# [1] "going"
# 
# [[3]]
# [1] "naieve_ass"    "your_synapsis"
# 
# [[4]]
# character(0)
# 
# [[5]]
# [1] "going"

感谢分享数据,下次请分享copy/pasteably。 dput 很不错。这是一个 copy/pasteable 输入:

v1 = c(
"do_i_need_to_even_say_it_do_i_well_here_i_go_anyways_chris_cornell_in_chicago_tonight"                                       ,
"going_to_see_harry_sunday_happiness"                                                                                         ,
"this_motha_fucka_stay_solid_foh_with_your_naieve_ass_mentality_your_synapsis_are_lacking_read_a_fucking_book_for_christ_sake",
"why_twitter_will_soon_become_obsolete_http_www.imediaconnection.com_content_23465_asp"                                       ,
"like_i_said_my_back_still_fucking_hurts_and_im_going_to_complain_about_it_like_no_ones_business_http_tumblr.com_x6n25amd5"  , 
"my_picture_with_kris_karmada_is_gone_forever_its_not_in_my_comments_on_my_mysapce_or_on_my_http_tumblr.com_xzg1wy4jj")

v2 = c("here_i_go", "going", "naieve_ass", "your_synapsis",   "my_picture_with",   "roll" )

我想在 stringi 包中使用 stri_extract_all_regex() 保留另一个选项。您可以直接从 v2 创建正则表达式并在 pattern.

中使用它
library(stringi)

stri_extract_all_regex(str = v1, pattern = paste(v2, collapse = "|"))

[[1]]
[1] "here_i_go"

[[2]]
[1] "going"

[[3]]
[1] "naieve_ass"    "your_synapsis"

[[4]]
[1] NA

[[5]]
[1] "going"

[[6]]
[1] "my_picture_with"