Reputation: 37
if have a vector (given) of words and I want to add the words to another vector, when a string starts with a vowel:
given = c("abc","def","oba")
expected=c("abc","oba")
I use the following code in R:
expected=""
given = c("abc","def","oba")
for (i in 1:length(given)){
start=substring(given[i], 1, 1)
if(start == "a" ||start == "e"|| start == "i" ||start == "o" ||start == "u")
{
expected[i]<-given[i]
}
else
{
""
}
}
The out is:
[1] "abc" NA "oba
And I wanted to have
[1] "abc" "oba
Can anyone help me to have a vector created without the NA?
How would I do that with a list?
Upvotes: 0
Views: 252
Reputation: 520898
You may use grepl
here:
given <- c("abc", "def", "oba")
expected <- given[grepl("^[aeiou]", given, ignore.case=TRUE)]
expected
[1] "abc" "oba"
The regex pattern ^[aeiou]
will match any string beginning with a vowel letter (either uppercase or lowercase).
Upvotes: 1