在R中,我如何用regex逐行比较两列中的模式行和不匹配行?

问题描述 投票:0回答:1

使用下面的代码,我设法得到了匹配的行,但是我如何得到不匹配的行呢?

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 1 1 London Hello London 2 3 Berlin asdBerlin

除了匹配的行,我还想得到不匹配的行。

帮助我得到不匹配的行.提前感谢。

r dplyr compare grepl
1个回答
2
投票

我想这可以帮助你。

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

创建于2020-06-03 重读包 (v0.3.0)


1
投票

您可以使用 str_detectstringr 在字符串和模式上进行了向量化,这样你就不必再使用 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))
© www.soinside.com 2019 - 2024. All rights reserved.