这个答案有两部分: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