使用 stringr 和 str_count 到 return 字符串中唯一单词的数量

Use stringr and str_count to return the number of unique words in a string

有没有办法使用 str_count 来计算字符串中的唯一单词数? 我想要下面的简单代码 return 2 而不是 6.

library(tidyverse)

string <- "Z AD Banana EW Z AD Z AD X" 

str_count(string, "Z|AD")

Returns: 6

一种方法是提取所有满足模式的值,然后对唯一值进行计数。

library(dplyr)
library(stringr)

n_distinct(str_extract_all(string, "Z|AD")[[1]])
#[1] 2

这可以用 base R 写成:

length(unique(regmatches(string, gregexpr("Z|AD", string))[[1]]))

我们可以使用

library(stringr)
library(purrr)
map_lgl(c("Z", "AD"), ~ str_detect(string, .x)) %>% sum
#[1] 2