davidd21
davidd21

Reputation: 43

write function to count number of vowels in a string

I was assigned the following homework question:

Write a function that will take a string as input and return the number of vowels in that string as the output

• Name the function get_vowel_count
• Make sure to document what the function does using comments in R

But when I feed the function a given string, it spits out 0 vowels in the console when there are clearly vowels in the string I give (e.g. "John Doe" contains three vowels)

I've changed the if statement a bit to better account for vowels, but I think the program will only count if the string is exactly an "a", "e", "i", etc.

I'm not sure what syntax exists to say "contains" rather than "is equal to"


mystr <- "John Doe"

get_vowel_count <- function(phrase) {
  counter <- 0
  for (i in phrase) {
    if ((i == 'a') | (i == 'e') | (i == 'i') | (i == 'o') | (i == 'u')) {
      counter <- counter + 1 
    }   
  }
  output <- paste("Your phrase has", counter, "vowels in it!" )
  print(output)
}

get_vowel_count(mystr)

The output is displaying 0 vowels, where, the expected should say "Your phrase has 3 vowels in it!"

Upvotes: 3

Views: 4436

Answers (3)

moodymudskipper
moodymudskipper

Reputation: 47330

I would remove all non vowels and count remaining characters :

nchar(gsub("[^aeiouy]","","John Doe", ignore.case = TRUE))
#> [1] 3

Upvotes: 2

BetterCallMe
BetterCallMe

Reputation: 768

In the for loop i was just passing whole string to if statement and loop was running only one time. Now i is passing a single character at a time and running for the length of the string.

It is good to first convert string to lowercase to avoid case conflict.

mystr <- "John Doe"
mystr_lower =tolower(mystr)

get_vowel_count <- function(phrase) {
  counter <- 0
  for (i in unlist(strsplit(phrase, ""))) {
    if ( i %in% c("a", "e", "i", "o", "u")) {
      counter <- counter + 1 
    }   
  }
  output <- paste("Your phrase has", counter, "vowels 
in it!" )
  print(output)
}

get_vowel_count(mystr_lower)

# Output: [1] "Your phrase has 3 vowels in it!"

Upvotes: 0

Ben Bolker
Ben Bolker

Reputation: 226557

for (i in phrase) doesn't work the way you think it does (in particular, it doesn't work the way it works in Python). In R, phrase is treated as a 1-element vector containing a single character string, not (as in Python) an ordered collection of letters.

So the first time through your loop, i is equal to "John Doe", which is not equal to any vowel. And your loop only repeats once.

  • You could use strsplit(phrase,"")[[1]] to split the string into a vector of letters

  • Or you could use something like (for i in seq(nchar(phrase)) ... if (substr(phrase,i,i)==...)

  • To simplify your test of vowels you could use something like if (substr(phrase,i,i) %in% c("a","e","i","o","u")) ...

Upvotes: 4

Related Questions