grepl
will work with mapply
:
Sample data frame:
title <- c('eggs and bacon','sausage biscuit','pancakes')
description <- c('scrambled eggs and thickcut bacon','homemade biscuit with breakfast pattie', 'stack of sourdough pancakes')
keyword <- c('bacon','sausage','sourdough')
df <- data.frame(title, description, keyword, stringsAsFactors=FALSE)
Searching for matches using grepl
:
df$exists_in_title <- mapply(grepl, pattern=df$keyword, x=df$title)
df$exists_in_description <- mapply(grepl, pattern=df$keyword, x=df$description)
And the results:
title description keyword exists_in_title exists_in_description
1 eggs and bacon scrambled eggs and thickcut bacon bacon TRUE TRUE
2 sausage biscuit homemade biscuit with breakfast pattie sausage TRUE FALSE
3 pancakes stack of sourdough pancakes sourdough FALSE TRUE
Update I
You could also do this with dplyr
and stringr
:
library(dplyr)
df %>%
rowwise() %>%
mutate(exists_in_title = grepl(keyword, title),
exists_in_description = grepl(keyword, description))
library(stringr)
df %>%
rowwise() %>%
mutate(exists_in_title = str_detect(title, keyword),
exists_in_description = str_detect(description, keyword))
Update II
Map
is also an option, or using more from tidyverse
another option could be purrr
with stringr
:
library(tidyverse)
df %>%
mutate(exists_in_title = unlist(Map(function(x, y) grepl(x, y), keyword, title))) %>%
mutate(exists_in_description = map2_lgl(description, keyword, str_detect))
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…