R - Grepl向量在向量

时间:2018-02-17 03:16:00

标签: r list vector lapply stringi

我有一个字符串向量(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" 

我可以返回向量列表的最快方式是,每个列表项代表v1中的每个向量项,每个向量项都是正则表达式匹配,其中v2中的项目出现在那个v1项,如下:

[[1]]
[1] "here_i_go"

[[2]]
[1] "going"

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

[[4]]

[[5]]
[1] "going"

[[6]]
[1] "my_picture_with"

2 个答案:

答案 0 :(得分:2)

如果你想要速度,我会使用stringi。您似乎没有任何正则表达式,只是固定模式,因此我们可以使用fixed stri_extract,并且(因为您不会提及如何处理多项匹配)我和#39;我假设只提取第一个匹配就好了,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"

感谢您分享数据,但下次请分享复制/粘贴。 dput对此很好。这是一个复制/粘贴输入:

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" )

答案 1 :(得分:2)

我想在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"