使用以下代码,我设法获得了匹配的行,但是如何获得不匹配的行?
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
除了匹配行,我也想要不匹配的行
帮助我获取不匹配的行。 提前谢谢。
我认为这可能会有所帮助:
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 由 reprex 软件包 (v0.3.0(
您可以使用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))