mardi 26 mai 2020

Printing certain elements of a character vector based on condition and deleting the others

I have a vector called fruits which contains names of 7 fruits. I want to print those fruit names which has more than or equal to 5 characters in the name.

fruits <- c("apple", "orange","pear","figs","avocado","plum", "kiwi")
j <- 1
while(j<=length(fruits)){

  if(nchar(fruits[j]>=5)){
    print(fruits[j])}
  else{
    remove(fruit[j])}
  j=j+1
}

Expected result is

[1] "apple"
[1] "orange"
[1] "avocado"

But what I get is

[1] "apple"
[1] "orange"
[1] "pear"
[1] "figs"
[1] "avocado"
[1] "plum"
[1] "kiwi"

It must also remove the fruit name with less than 5 character from the vector.

Aucun commentaire:

Enregistrer un commentaire