r - 从另一个df中的字符串中检测一个df中的多个字符串,如果检测到,则返回检测到的字符串
问题描述
我正在学习使用 R,所以请多多包涵。
我有一个谷歌游戏商店应用程序数据集(master_tib)。每行都是一个 Play 商店应用程序。有一列标题为描述,其中包含有关应用程序功能的文本。
master_tib
App Description
App1 Reduce your depression and anxiety
App2 Help your depression
App3 This app helps with Anxiety
App4 Dog walker app 3000
我还有一个 df 的标签 (master_tags),其中包含我预定义的重要单词。有一个标题为标签的列,每行包含一个标签。
master_tag
Tag
Depression
Anxiety
Stress
Mood
我的目标是根据描述中标签的存在,用 master_tags df 中的标签标记来自 master_tib df 的应用程序。然后它将在新列中打印标签。最终结果将是一个 master_tib df,如下所示:
App Description Tag
App1 Reduce your depression and anxiety depression, anxiety
App2 Help your depression depression
App3 This app helps with anxiety anxiety
App4 Dog walker app 3000 FALSE
以下是我迄今为止使用 str_detect 和 mapply 的组合所做的工作:
# define function to use in mapply
detect_tag <- function(description, tag){
if(str_detect(description, tag, FALSE)) {
return (tag)
} else {
return (FALSE)
}
}
index <- mapply(FUN = detect_tag, description = master_tib$description, master_tags$tag)
master_tib[index,]
不幸的是,只有第一个标签被传递。
App Description Tag
App1 Reduce your depression and anxiety depression
而不是所需的:
App Description Tag
App1 Reduce your depression and anxiety depression, anxiety
我还没有将结果打印到新列中。很想听听任何人的见解或想法,并为我糟糕的 R 技能提前道歉。
解决方案
您可以将 master_tag
usingstr_c
和 use中的单词组合起来str_extract_all
以获取与模式匹配的所有单词。
library(stringr)
master_tib$Tag <- sapply(str_extract_all(tolower(master_tib$Description),
str_c('\\b', tolower(master_tag$Tag), '\\b', collapse = "|")),
function(x) toString(unique(x)))
master_tib$Tag
#[1] "depression, anxiety" "depression" "anxiety" ""
数据
master_tag <- structure(list(Tag = c("Depression", "Anxiety", "Stress", "Mood"
)), class = "data.frame", row.names = c(NA, -4L))
master_tib <- structure(list(App = c("App1 ", "App2 ", "App3 ", "App4 "
), Description = c("Reduce your depression and anxiety", "Help your depression",
"This app helps with Anxiety", "Dog walker app 3000")), row.names = c(NA,
-4L), class = "data.frame")
推荐阅读
- docfx - Docfx 俄语语言搜索
- node.js - 常规函数中的“this”与 ES6 中的胖箭头函数,以 Mongoose 为例进行说明
- jquery - Why doesn't my jQuery-UI dialog work even though all script references are included?
- macos - 如何使用 atos 正确符号化来自 OSReportWithBacktrace 的地址?
- css - 为什么我不能居中这个文本?
- api - API 网关是否应该与业务逻辑耦合/分离
- common-lisp - Common Lisp SBCL 中函数调用的性能
- python - python函数的python进度条
- json - 使用 Post 方法将数据传递到 SignalR Hub 到 Web Api 返回:远程服务器返回错误:(404)未找到
- php - 如何验证单词是否在数组中并获取数组位置值?