Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get matching characters?

Tags:

r

I'm trying to get common characters from two separate vectors.

Example:

x <- c("abcde")
y <- c("efghi")
df <- data.frame(x, y)

Desired output

    x       y     z 
abcde   efghi     e     
lmnop   uvmxw     m

I've tried something like this, but it is a bad result:

df |> mutate(m = unique(x, y))

If there are multiple matches, returning a list would work great.

like image 317
writer_typer Avatar asked Nov 30 '25 12:11

writer_typer


1 Answers

str_intersect <- function(s1,s2) {
  paste0(intersect(strsplit(s1,"")[[1]],strsplit(s2,"")[[1]]),collapse = "")
}

x <- c("abcde","abc")
y <- c("efghi","b")
df <- data.frame(x, y)

library(dplyr)
df %>%
  rowwise() %>%
  mutate(m = str_intersect(x,y))
like image 169
Eric Avatar answered Dec 03 '25 02:12

Eric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!