我正在计算 expected
列中有多少个字符出现在 read
列中。
它们可能以不同的顺序出现,不应计算两次。
比如在这个df中
df <- tibble::tibble(expected=c("AL0","CP1","NM3","PK9","RM2"),
read=c("AL0X24",
"CXP44",
"MLN",
"KKRR9",
"22MMRRS"
))
结果应该是:
result <- c(3,2,2,2,3)
最佳答案
str_extract/n_distinct
选项。使用paste
将[
, ]
与'expected'列字符串包裹起来,从'中提取'expected'中显示模式的所有字符读取'并使用 n_distinct
library(stringr)
library(dplyr)
with(df, sapply(str_extract_all(read, paste0("[", expected, "]")), n_distinct))
#[1] 3 2 2 2 3
或者另一个选项是 str_replace_all
和 str_count
。在这里,我们使用 str_replace_all
删除“read”中的重复字符,并通过粘贴 [
和 ]使用它来计算“expected”中的字符
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
关于r - 计算一列中有多少个字符出现在另一列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63982895/