【问题标题】:Using R, how do I test a dataframe of phrases to see if it contains keywords使用 R,我如何测试短语数据框以查看它是否包含关键字
【发布时间】:2015-09-29 21:48:10
【问题描述】:

我有 2 个数据框。一个包含这样的搜索词组

搜索.短语 1 快 2 只棕色狐狸跳跃 3过懒 5 条狗 6 为什么 7没人知道 ...

和另一个包含关键字

关键字 1 快速 2懒惰 3 条狗 4 知道 ...

理想情况下,我想找出哪些搜索词组包含一个或多个(布尔值或计数)这样的关键字

search.phrases keyword.found 1 快速 TRUE 2 棕狐跳 FALSE 3 过懒 TRUE 5 狗 TRUE 6 为什么是假的 7 没有人知道 TRUE ...

我已经尝试了一段时间,但我很难过。非常感谢任何帮助。

很多爱

G

【问题讨论】:

  • 您能否展示一下您尝试过的内容。很多爱。
  • 嗨詹姆斯,我发现我可以使用 grepl 一次手动完成一个关键字,然后尝试使用一些应用方法,但我对 R 还是很陌生,所以没有什么能接近。对不起。
  • 这篇文章有很多积极的影响。我喜欢它
  • 嘿,理查德,你年轻有才华,世界就是你的牡蛎。加油!

标签: r regex dataframe


【解决方案1】:

您可以使用grepl()

rgx <- paste(as.character(df2$keywords), collapse = "|")
df$keyword.found <- grepl(rgx, df$search.phrases)

结果:

   search.phrases keyword.found
1       the quick          TRUE
2 brown fox jumps         FALSE
3   over the lazy          TRUE
5             dog          TRUE
6             why         FALSE
7    nobody knows          TRUE

数据:

df2 <- structure(list(keywords = structure(c(4L, 3L, 1L, 2L), .Label = c("dog", 
"knows", "lazy", "quick"), class = "factor")), .Names = "keywords", class = "data.frame", row.names = c("1", 
"2", "3", "4"))
df <- structure(list(search.phrases = structure(c(5L, 1L, 4L, 2L, 6L, 
3L), .Label = c("brown fox jumps", "dog", "nobody knows", "over the lazy", 
"the quick", "why"), class = "factor")), .Names = "search.phrases", class = "data.frame", row.names = c("1", 
"2", "3", "5", "6", "7"))

【讨论】:

    【解决方案2】:
    c("the quick fox", "had a dog", "named bruce") -> phrases
    c("quick", "bruce") -> keywords
    library(stringr)
    str_split(phrases, " ") -> phrase_list
    sapply(phrase_list, function(x) any(ifelse(x %in% keywords, TRUE, FALSE))) -> z
    

    【讨论】:

    • 这不仅解决了今天的问题,而且您也无意中解决了昨天的问题。不错的工作。谢谢
    猜你喜欢
    • 2011-03-05
    • 2023-03-12
    • 2022-11-28
    • 1970-01-01
    • 2013-05-11
    • 2016-01-31
    • 1970-01-01
    • 2011-05-07
    • 1970-01-01
    相关资源
    最近更新 更多