Sushant Shelke
Sushant Shelke

Reputation: 57

In R, how do I compare for pattern and mismatched rows from two columns with a regex, row-by row?

Using below code i managed to get the matched rows but how can i get the mismatch rows?

ABData <- data.frame(a = c(1,2,3,4,5),b = c("London", "Oxford", "Berlin","Hamburg", "Oslo"),c = c("Hello London","No London","asdBerlin","No Match","OsLondonlohama"))

match<- ABData %>% rowwise() %>% filter(grepl(b,c))

Match Result:

a b c
1 1 London Hello London 2 3 Berlin asdBerlin

along with the match rows i want mismatch rows as well

Help me to get mismatch rows. Thanks in advance.

Upvotes: 0

Views: 285

Answers (2)

Ronak Shah
Ronak Shah

Reputation: 388862

You can use str_detect from stringr which is vectorized over string as well as pattern so that you don't have to use rowwise.

subset(ABData, !stringr::str_detect(c, b))

#  a       b              c
#2 2  Oxford      No London
#4 4 Hamburg       No Match
#5 5    Oslo OsLondonlohama

If you want to use it with dplyr :

library(dplyr)
ABData %>% filter(!stringr::str_detect(c, b))

Upvotes: 1

MarBlo
MarBlo

Reputation: 4524

I think this could help:

library(tidyverse)
ABData <- data.frame(a = c(1,2,3,4,5),
                     b = c("London", "Oxford", "Berlin","Hamburg", "Oslo"),
                     c = c("Hello London","No London","asdBerlin","No Match","OsLondonlohama"))

match <- ABData %>% 
  rowwise() %>% 
  filter_at(.vars= vars(c), all_vars(grepl(b,.)))
match
#> Source: local data frame [2 x 3]
#> Groups: <by row>
#> 
#> # A tibble: 2 x 3
#>       a b      c           
#>   <dbl> <chr>  <chr>       
#> 1     1 London Hello London
#> 2     3 Berlin asdBerlin

no_match <- ABData %>% 
  rowwise() %>% 
  filter_at(.vars= vars(c), all_vars(!grepl(b,.)))
no_match
#> Source: local data frame [3 x 3]
#> Groups: <by row>
#> 
#> # A tibble: 3 x 3
#>       a b       c             
#>   <dbl> <chr>   <chr>         
#> 1     2 Oxford  No London     
#> 2     4 Hamburg No Match      
#> 3     5 Oslo    OsLondonlohama

Created on 2020-06-03 by the reprex package (v0.3.0)

Upvotes: 2

Related Questions