How to string count unique values in data strings

Viewed 305

I am trying to find common words having 5 unique vowels (i.e: "aeiuo" without in a single word and without repetition)

I tried this:

library(tidyverse)
x<-c("appropriate","associate","available","colleague","experience","encourage","encouragi","associetu")
x[str_count(x,"[aeiuo]")>4]

Note that words ("encouragi" and "associetu") were used for the purpose of verifying my intended answer

the results I am generating are the following:

[3] "available"   "colleague"  
[5] "experience"  "encourage"  
[7] "encouragi"   "associetu"

While I wanted to get only: "encouragi" "associetu" which fulfill the criteria of having 5 distinct vowels (i.e: "aeiuo").

Is there any function to serve as string_count_unique?? if yes, which one? if not, what other function might you recommend me to use so that I meet the set criteria?

thank you in advance for your help!

4 Answers

One option could be:

x[lengths(lapply(str_extract_all(x, "a|e|i|u|o"), unique)) == 5]

[1] "encouragi" "associetu"

Maybe strsplit could help you

> x[sapply(strsplit(x,""),function(v) sum(unique(v)%in%c("a","e","i","o","u"))>4) ]
[1] "encouragi" "associetu"

Here's a way to do it using strsplit and setdiff. We loop over each string using sapply, we split each string into its letters, then we check if all vowels are present in the vector resulting from strsplit. If the length of the setdiff is greater than 0, one or more vowels are not present in the string.

keep <- sapply(x, FUN = function(x){
  length(setdiff(c("a", "e", "i", "o", "u"), el(strsplit(x, "")))) == 0
})

x[keep]

# [1] "encouragi" "associetu"

The problem with your code is that you are counting if the sum of ANY of aeiou is >4. What you want is to check that the count of a is >0 AND that the count of e is >0 and so on. So you could check the following:

x[str_count(x,"[a]")>0 & str_count(x,"[e]")>0 & str_count(x,"[i]")>0 & str_count(x,"[o]")>0 & str_count(x,"[u]")>0]
Related