在 R 中,如何使用正则表达式逐行比较两列中的模式行和不匹配行?

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

使用下面的代码我设法得到了匹配的行,但是我怎样才能得到不匹配的行?

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))

比赛结果:

a b c<br> 1 1 伦敦 你好伦敦 2 3 柏林 asdBerlin

除了匹配行,我还想要不匹配的行

帮助我获取不匹配的行。 提前致谢。

我认为这会有所帮助:

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

reprex package (v0.3.0)

于 2020-06-03 创建

您可以使用 stringr 中的 str_detect,它在字符串和模式上进行了矢量化,因此您不必使用 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

如果你想和dplyr一起使用:

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