计算字符串中不同的字母?

Count distinct letters in a string?

如何计算字符串中不同的字符数?

模拟数据

d = tibble(word = c("aaa", "abc", "abcde"))

如何编写一个新变量来计算字符串中区字母的数量?换句话说,这应该给出如下答案:

first row = 1
second row = 3
third row = 5

PS!特别欢迎 Tidyverse 解决方案!

在基础 R 中,

sapply(strsplit(d$word, ''), function(x) length(unique(x)))
#[1] 1 3 5

同样的逻辑可以写成tidyverse-

library(tidyverse)

d %>%
  mutate(unique_n = map_dbl(str_split(word, ''), n_distinct))

#  word  unique_n
#  <chr>    <dbl>
#1 aaa          1
#2 abc          3
#3 abcde        5

这是一个基于正则表达式的方法:

x <- "abcabcabc"
output <- gsub("([a-z])(?=.*\1)", "", x, perl=TRUE)  # "abc"
nchar(output)

[1] 3

想法是去除字符串中的所有重复字符,留下仅包含唯一字符的字符串。