Find & Identify

This would be one way to do it

df <-data.frame(stringsAsFactors=FALSE,
                 name = c("AAAA_AAAB", "AAAC_AAAD", "AAAD_AAAE",
                          "AAAB_AAAA", "AAAD_AAAC", "AAAE_AAAD",
                          "AAAB_AAAA")
)

library(tidyverse)

df %>% 
    separate(name, c("first", "second"), remove = FALSE) %>% 
    mutate(name_ID = row_number(),
           Confronted_Traffic = map2(first, second, ~str_which(name, paste0(.x, "_", .y,"|", .y, "_", .x)))) %>% 
    unnest(Confronted_Traffic) %>%
    filter(name_ID != Confronted_Traffic) %>% 
    select(-first, -second)
#> # A tibble: 10 x 3
#>    name      name_ID Confronted_Traffic
#>    <chr>       <int>              <int>
#>  1 AAAA_AAAB       1                  4
#>  2 AAAA_AAAB       1                  7
#>  3 AAAC_AAAD       2                  5
#>  4 AAAD_AAAE       3                  6
#>  5 AAAB_AAAA       4                  1
#>  6 AAAB_AAAA       4                  7
#>  7 AAAD_AAAC       5                  2
#>  8 AAAE_AAAD       6                  3
#>  9 AAAB_AAAA       7                  1
#> 10 AAAB_AAAA       7                  4

Created on 2019-11-06 by the reprex package (v0.3.0.9000)

Note: Please use proper code formatting, here is how to do it

1 Like