按列内容匹配的字符串

String matching by contents of columns

我有一个巨大的数据框和几个关键词(都是非数字)。我想编写 R 代码来遍历整个数据框并查找句子包含一个或多个这些关键词的列。然后如果有匹配将关键字放在新列的同一行中(如果有多个匹配则将它们都用逗号分隔或也放在新列中)。

例如,鉴于下面的数据,我想添加一个列来显示与这些关键字匹配的内容:

keywords<- c("Smith", "Carla")

然后我希望结果看起来像这样:

**Names**          **Matching**

John Smith          Smith
Carla Smith         Carla, Smith **(could be same column or different column)**
Smith Smith         Smith
John Carla          Carla

我尝试使用 grep:

 Matching <- Data[grepl("carla",Data$Names), ]

你能帮帮我吗?

这个答案分为两部分:OP 编辑​​了他的答案,但第一部分似乎仍然有用

第 1 部分:OP 的原始问题

将您的任务分解为更小的任务并提供最小示例通常会有所帮助。

所以这是一些数据

shoes <- c("cookie", "nike", "adidas")
drinks <- c("water", "lemon", "cookie")
clothes <- c("pants", "cookie", "sweater")
df <- data.frame(shoes, drinks, clothes, stringsAsFactors = FALSE)
df

现在让我们看看@akrun 的评论,看看我们是否可以从单个列中获取字符串 "cookie":

library(stringr)
str_extract_all("cookie", df$shoes) == "cookie"

那么,这行得通,现在我们需要对所有列执行此操作。为了帮助我们编写一个小函数并在列上循环:

extract_cookie <- function(x) {
    x <- as.character(x) # just to safeguard against non-string values .
    str_extract_all("cookie", x) == "cookie"
}
sapply(df, extract_cookie)
     shoes drinks clothes
[1,]  TRUE  FALSE   FALSE
[2,] FALSE  FALSE    TRUE
[3,] FALSE   TRUE   FALSE

第 2 部分:(在 OP 编辑​​问题后)

既然你现在提到你自己的努力使用 grepl..

people <- c("John Smith", "Carla Smith", "Smith Smith", "John Carla")
persons <- data.frame(people, stringsAsFactors = FALSE)

persons$smiths <- grepl("Smith", persons$people)
persons$carlas <- grepl("Carla", persons$people)
persons$perfectMatch <- persons$smiths == TRUE & persons$carlas == TRUE

persons$smiths2 <- ifelse(grepl("Smith", persons$people), "Smiths", "")
persons$carlas2 <- ifelse(grepl("Carla", persons$people), "Carla", "")
persons$perfectMatch2 <- ifelse(persons$perfectMatch == TRUE, 
                                    paste(persons$carlas2, persons$smiths2), "")
persons

       people smiths carlas perfectMatch smiths2 carlas2 perfectMatch2
1  John Smith   TRUE  FALSE        FALSE  Smiths                      
2 Carla Smith   TRUE   TRUE         TRUE  Smiths   Carla  Carla Smiths
3 Smith Smith   TRUE  FALSE        FALSE  Smiths                      
4  John Carla  FALSE   TRUE        FALSE           Carla