dimanche 2 décembre 2018

Looping through user word input in R

I have a question regarding creating a function in R that will take a user input and essentially check:

  1. String item is less than or equal to three words
  2. Test to see if there data is in a dataframe of restricted words
  3. If it passes both of those conditions then I want it to return the pasted string

I have put this code together so far but I am receiving Error: unexpected else in else. Also, I'd like to create a condition that can doesn't explicitly test for the length two or length three and test all of those elements explicitly.

Here is a simplified repeatable version of what I trying to do:

library(tokenizers)
a <- c("alpha", "beta", "gamma", "delta", "epsilon")
a <- as.data.frame(a)
colnames(a) <- c("words")

test <- function(phrase){
  words <- tolower(phrase)
  words <- tokenize_words(words)
  if(length(words[[1]])> 3){
    "Phrase too long"
  } else if(length(words[[1]]) == 2){
      if(words[[1]][1] %in% a$words){
        "Not Approved"
      } else if(words[[1]][2] %in% a$word){
        "Not Approved"
      } else 
      {
          words[[1]]
        }
    } 

  else {
    if(words[[1]] %in% a$word){
      "Not Approved"
    }
    else {words[[1]]}
  }
}

test("Alpha Test")

This should return a "Not Approved" on it; but if it was length 3 or length 1 and contained one of the restricted words I'd want it to return not approved.

Thanks!

Aucun commentaire:

Enregistrer un commentaire