gpt4 book ai didi

r - 从另一个 df 中的字符串检测一个 df 中的多个字符串,如果检测到,则返回检测到的字符串

转载 作者:行者123 更新时间:2023-12-01 21:34:45 24 4
gpt4 key购买 nike

我正在学习使用 R,所以请多多包涵。

我有一个 google play 商店应用程序数据集 (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 技能提前道歉。

最佳答案

您可以使用 str_c 组合来自 master_tag 的单词,并使用 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")

关于r - 从另一个 df 中的字符串检测一个 df 中的多个字符串,如果检测到,则返回检测到的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62123513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com