【问题标题】:In R, how do I compare for pattern and mismatched rows from two columns with a regex, row-by row?在 R 中,如何使用正则表达式逐行比较两列中的模式和不匹配行?
【发布时间】:2020-06-03 11:40:25
【问题描述】:

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

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

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

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

【问题讨论】:

  • 您可以使用! 得到否定。喜欢这个!grepl(b,c)

标签: r dplyr compare grepl


【解决方案1】:

我认为这会有所帮助:

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 年 6 月 3 日创建

【讨论】:

  • 谢谢@MarBlo 它也可以工作......我们也可以使用“!”像“!grepl”
【解决方案2】:

您可以使用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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多