Count how many characters from a column appear in another column

Viewed 42

I am trying to count how many characters from column expected appear in column read. They may appear in different order and they should not be counted twice.

For example, in this df

df <- tibble::tibble(expected=c("AL0","CP1","NM3","PK9","RM2"),
                     read=c("AL0X24",
                            "CXP44",
                            "MLN",
                            "KKRR9",
                            "22MMRRS"
                     ))

The result should be:

result <- c(3,2,2,2,3)
2 Answers

One option could be:

mapply(function(x, y) sum(x %in% unique(y)),
       x = strsplit(df$expected, ""),
       y = strsplit(df$read, ""))

[1] 3 2 2 2 3

An option with str_extract/n_distinct. Wrap the [, ] with the 'expected' column string using paste, extract all the characters that show the pattern in 'expected' from 'read' and count the number of distinct elements with n_distinct

library(stringr)
library(dplyr)
with(df, sapply(str_extract_all(read, paste0("[", expected, "]")), n_distinct))
#[1] 3 2 2 2 3

Or another option with str_replace_all with str_count. Here, we remove the duplicate characters in 'read' with str_replace_all and use that to count the characters in 'expected' by pasteing the [, and ]

df %>% 
    mutate(Count = str_count(str_replace_all(read, "(\\w)\\1+", "\\1"), 
        str_c("[", expected, "]")))
# A tibble: 5 x 3
#  expected read    Count
#  <chr>    <chr>   <int>
#1 AL0      AL0X24      3
#2 CP1      CXP44       2
#3 NM3      MLN         2
#4 PK9      KKRR9       2
#5 RM2      22MMRRS     3
Related