rstringjointidyverse

How to get intersection of strings in R tidy? Not union


I have two vectors of strings and I want to make an intersection and concatenate them into a new vector. I found a complicated way to do it. Is there a tidy function to use?

library(dplyr)
library(tibble)
string_a <- c("ab", "bc", "cd", "df", "aq")
string_b <- c("ac", "bc", "bd", "df", "aq")

string_a <- string_a %>%  enframe() %>% dplyr::select(-name)

string_b <- string_b %>%  enframe() %>% dplyr::select(-name)
inter_str <- inner_join(string_a, string_b) %>%
  pull(value)


Solution

  • This is one of those occurences, where base has a straigthforward, easy-to-read, and perfect solution.

    > string_a <- c("ab", "bc", "cd", "df", "aq")
    > string_b <- c("ac", "bc", "bd", "df", "aq")
    > base::intersect(string_a, string_b)
    [1] "bc" "df" "aq"