Search code examples
rfor-loopcharacterstringr

making for loop for character vector in R


char_vector <- c("Africa", "identical", "ending" ,"aa" ,"bb", "rain" ,"Friday" ,"transport") # character vector 
  1. Suppose I have the above character vector I would like to create a for loop to print on the screen only the elements in a vector that have more than 5 characters and starts with a vowel and also delete from the vector those elements that do not start with a vowel

  2. I created this for loop but it also gives null characters

for (i in char_vector){
    if (str_length(i) > 5){
    i <- str_subset(i, "^[AEIOUaeiou]")
    print(i)
    
    } 
}
  1. The result for the above is
[1] "Africa"
[1] "identical"
[1] "ending"
character(0)
character(0)
  1. My desired result would only be the first 3 characters

  2. I'm really new to R and facing huge difficulty with creating a for loop for this problem. Any help would be greatly appreciated!


Solution

  • With stringr functions, you'd rather use str_detect instead of str_subset, and you can take advantage of the fact that those functions are vectorized:

    library(stringr)
    char_vector[str_length(char_vector) > 5 & str_detect(char_vector, "^[AEIOUaeiou]")]
    #[1] "Africa"    "identical" "ending"   
    

    or if you want your for loop as a single vector:

    vec <- c()
    for (i in char_vector){
      if (str_length(i) > 5 & str_detect(i, "^[AEIOUaeiou]")){
        vec <- c(vec, i)
      } 
    }
    vec
    # [1] "Africa"    "identical" "ending"