Home > Mobile >  For loops in r, using two vairables in a vector
For loops in r, using two vairables in a vector

Time:03-29

extract_vowels <- function(word) {
        split_word <- strsplit(word,"")[[1]]
        empty_vowels = c()
        for (letter in split_word) {
            if(tolower(letter) %in% c('a','e','i','o','u')) {
                empty_vowels <- c(empty_vowels, tolower(letter))
            }
        }
        empty_vowels
    }

extract-vowels('preHistoric') 

Above code is giving us all the vowels that are included. But when we say,

empty_vowels <- c(tolower(letter)) 

and we eliminate the empty vowels object from the vector then it gives us "i" not all the vowels, why is that? It should've given the all vowels because empty_vowels is an empty object which we defined it before the 'for loop' so it has zero values in it, so why are we writing c(empty_vowels, tolower(letter)) and actually that code line IS giving us the all vowels. How?

CodePudding user response:

empty_vowels <- c(tolower(letter)) will overwrite empty_vowels with tolower(letter). Each time within the loop the old value of empty_vowels is overwritten and a new value is asaigned.

The last vowel in "preHistoric" is an "i" so the last round of the loop, that is assigned to 'empty_vowel'.

CodePudding user response:

When your function finds the first vowel, that vowel is an "e", so empty_vowels <- c(tolower(letter)) is equivalent to empty_vowels <- "e". In other words, it doesn't matter at all what empty_vowels was before this expression. You're throwing all that away, and turning it into "e".

Thus, when it finds the second vowel, which is "i", the problematic code will just do that again. Even if empty_vowels == "e" at this point, empty_vowels <- c(tolower(letter)) will not even notice, and is equivalent to empty_vowels <- "i". then empty_vowels == "i", and the "e" is completely forgotten.

In the other case, empty_vowels <- c(empty_vowels, tolower(letter)) will preserve the previous contents of empty_vowels. Since empty_vowels is empty the first time around, it will just turn empty_vowels into "e". But from the second vowel onwards, the new vowel will be added to the current list of vowels that were found, and you will end with an object containing all of the vowels. (Not just the last one).

  • Related