首页 > 解决方案 > 可变文本包含多个模式

问题描述

我需要知道match变量是否包含在url变量中:

df1 = data.frame(match  = c("2234436803329252","460696711422302"), stringsAsFactors = F)

df2 = data.frame(url = c("https://business.facebook.com/460696711422302/", "https://twitter.com/status/1192745040302477312"),stringsAsFactors = F)

df1 %>% mutate(is_in_url = str_detect(df1$match,fixed(df2$url,ignore_case = T )

它返回一个向量c(FALSE, FALSE),但“ https://business.facebook.com/460696711422302/ ”包含“ 460696711422302 ”。有资源dplyrstringr图书馆吗?

标签: rregexdplyrpurrrstringr

解决方案


问题是只string_detect检查匹配的组件。考虑这个简单的例子:

> str_detect(c("a", "b"), c("b", "a"))
[1] FALSE FALSE
> str_detect(c("a", "b"), c("a", "b"))
[1] TRUE TRUE

所以字符串的第一个组件只检查模式的第一个组件。这就是为什么在你的情况下你有c(FALSE, FALSE)结果。

你可以试试这个:

match <- c("2234436803329252","460696711422302")
url <- c("https://business.facebook.com/460696711422302/", "https://twitter.com/status/1192745040302477312")

sapply(url, function(x) any(str_detect(x, match)))
https://business.facebook.com/460696711422302/ https://twitter.com/status/1192745040302477312 
                                          TRUE                                          FALSE 

推荐阅读