vijayvithal
vijayvithal

Reputation: 581

R grep pattern in a column

I have a dataframe where one column is pattern and another is string. I want to iterate over each row check if the rows's string contains row's pattern and update the Matches column with T/F status I tried

df<- df%>%mutate(Matches=grepl(pattern,string))

and got the following error.

argument 'pattern' has length > 1 and only the first element will be used

I understand that in the above code grepl is trying to read all rows of pattern column instead of the current row.

Is there any function which does this job or do I need to use a for loop and manually iterate over each row?

Upvotes: 2

Views: 11541

Answers (1)

akrun
akrun

Reputation: 887128

If we need to compare the 'string' with 'pattern' in each row, then use rowwise() from dplyr

library(dplyr)
df %>% 
    rowwise() %>% 
    mutate(Matches = grepl(pattern, string))    
# A tibble: 3 × 3
#  pattern string Matches
#    <chr>  <chr>   <lgl>
#1      sl  sling    TRUE
#2      ab   dare   FALSE
#3      cd   care   FALSE

It can also be done with mapply from base R

df$Matches <- mapply(grepl, df$pattern, df$string)

data

df <- data.frame(pattern = c("sl", "ab", "cd"),
       string = c("sling", "dare", "care"), stringsAsFactors=FALSE)

Upvotes: 12

Related Questions