lundi 28 août 2017

R: Nesting an if statement within a While loop

I want to nest an "if" condition within a while loop, but I keep getting Error: unexpected '}' in " }"

I've written a line of code that checks if any pattern from a vector is present within a text string:

i <- 1
while (i <= 6) {
  print(i)
  print(Names[i])
  print(grepl(Names[i], test))
  i <- i+1
}

This works fine at spotting the names in the vector: ``

[1] 1
[1] "A"
[1] FALSE
[1] 2
[1] "B"
[1] FALSE
[1] 3
[1] "C"
[1] FALSE
[1] 4
[1] "D"
[1] FALSE
[1] 5
[1] "E"
[1] FALSE
[1] 6

Now I'm trying to have it display only the names that are indeed present in the string of text, for that I tried the following if condition that returns the afore mentioned error:

i <- 1
while (i <= 6) {
  print(i)
  print(Names[i])
  if (grepl(Names[i], test)) = TRUE {
    print(grepl(Names[i], test)) }
  i <- i+1
    }

I guessed it would print i, then the name of at that position of i, then check if the IF condition is TRUE, but instead it only returns errors. What am I doing wrong, am I forgetting to set a break condition or something?

Aucun commentaire:

Enregistrer un commentaire