首页 > 解决方案 > 匹配数据框中列的文本

问题描述

我正在寻找出现在搜索字符串中的关键字(在这种情况下,是一个研究问题)。我想我已经接近了,但我不太确定我遇到了什么问题。我的数据框看起来像这样:

Q1                                                     keywords
How do you assess strategic deterrence messaging?      Deterrence messaging effects perception assessment
An energy transition for green growth                  Energy transition sustainable
Some other research question here                      research keywords topics etc

whereQ1指的是问题,thekeywords是单词列表(在这种情况下,清除了 AND、NOT 和 OR 的清理布尔搜索)。我要确定的是字符串中是否keywords出现了任何匹配项Q1,找到匹配项,并计算这种情况发生的频率(所以我可以说它keywords出现在column1 n % 的时间里,在column2 n % 的时间里...... .)。

这是我开始的地方,使用tidyverse

df_final <- df %>% 
  mutate(matches = str_extract_all(
    Q1,
    str_c(df$keywords, collapse = "|") %>% regex(ignore_case = T)),
    match = map_chr(matches, str_c, collapse = ", "),
    count = map_int(matches, length)
  )

但我没有得到任何匹配。我假设它可能与我的keyword专栏有关?是否需要将其转换为向量或逗号分隔的列表才能正常工作?提前感谢您的建议!

编辑:来自的示例输出dput()

structure(list(Q1 = c("Assessing the effects of strategic deterrence messaging in the cognitive dimension", 
"How do you assess effects of strategic deterrence messaging?", 
"Determine Strategic Implications of Climate Change to USG/DoD"
), keywords = c("Deterrence messaging effects perception assessment", 
"political philosophy sociology social sciences history marketing power structure government governing class bourgeoisie social class military class ruling class governing class", 
"Climate Change Strategic Global Warming Strategic Climate Change Policy Global Warming Policy"
)), .Names = c("Q1", "keywords"), row.names = c(NA, -3L), class = c("tbl_df", 
"tbl", "data.frame"))

标签: rdplyrstringr

解决方案


可能不是最佳的,但也许有帮助。我补充说tolower(),因为我假设您不在乎威慑或威慑。

a <-tolower(unique(unlist(strsplit(df$keywords, " "))))

dfcounter <- data.frame(table(tolower(unlist(strsplit(df$Q1, " ")))),stringsAsFactors = F)

dfcounter[match(a,dfcounter$Var1,nomatch = 0),]

推荐阅读