r - 可变文本包含多个模式
问题描述
我需要知道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 ”。有资源dplyr
和stringr
图书馆吗?
解决方案
问题是只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
推荐阅读
- python - Python硒:::
- php - 每当 session_start() 在 php 中被调用时,cookie 值一直在变化
- kotlin - Kotlin 协程 isActive 即使协程没有运行也为真
- regex - 在句子中查找单词序列(字符串)的位置
- arrays - 在本机反应中切换数组项?
- r - 可以检查时间(无日期)是否在特定的日期时间间隔内?
- python - 输入包含 NaN、无穷大或对于 dtype('float32') 来说太大的值。推荐系统django
- c# - 当我运行 dotnet run 时,为什么 dotnet restore 命令会在后台运行?
- php - 从用户键入的字符串中获取特定值
- java - 在 Travis 上本地通过的构建失败