Jiakai Dong
Jiakai Dong

Reputation: 49

How can I Iimit the data that the user write in R?

checknames <- function(){
  gamers <- c("Rebeca","Luis","Paco")
  games <- c(3,2,7)
  scores <- c(100,110,50)
  table <- data.frame(gamers,games,scores)
  r=0
  p=0
  repeat{
    print("Name Player 1: ")
    name1=scan(,what="character",1)
    if(any(name1==gamers)){
      r=readline(prompt = "This player is already in the file. Would you like to change the name? \n 1. Yes \n 2. No \n Select an option: ")
    }
    else{
      r <- 0
    }
    if(r==2){
      break
    }
    if(r==0){
      gamers=c(gamers,name1)
      name1 <- data.frame(gamers=name1,games="1",scores="100")
      table <- rbind(table,name1)
      break
    }
  }
  table
  repeat{
    print("Name Player 2: ")
    name2=scan(,what="character",1)
    if(any(name2==gamers)){
      p=readline(prompt = "This player is already in the file. Would you like to change the name? \n 1. Yes \n 2. No \n Select an option: ")
    }
    else{
      p <- 0
    }
    if(p==2){
      break
    }
    if(p==0){
      gamers=c(gamers,name2)
      name2 <- data.frame(gamers=name2,games="1",scores="100")
      table <- rbind(table,name2)
      break
    }
  }
  table
}
table <-checknames()

Hi everyone, I did a code that ask the user to enter 2 names, and if this name is in the table, it should ask the user if he wants to change his name. The problem is, when the question of if he wants to change his name, I give him 2 option: "1" for Yes, and "2" for No, and I want that when the user enter other caracters like "t" or "7" (for example), the code said: "This option is unavailable, please chose another one" or something like that, and ask another time the question of if he want to change his name. Hope you can help me, thank you very much!

Upvotes: 1

Views: 61

Answers (1)

Daniel O
Daniel O

Reputation: 4358

You could restructure the p check if statements into an ifelse that check the cases you want in order if p=2 then if p=0 and lastly if p not= 1

 p=1
  repeat{

    if(p==1){
      print("Name Player 2: ")
      name2=scan(,what="character",1)

      if(any(name2==gamers)){
        p=readline(prompt = "This player is already in the file. Would you like to change the name? \n 1. Yes \n 2. No \n Select an option: ")
        if(p==0){p<-99}
      }else{
        p <- 0
      }

    }else if(p==2){
      break
    }else if(p==0){
      gamers=c(gamers,name2)
      name2 <- data.frame(gamers=name2,games="1",scores="100")
      table <- rbind(table,name2)
      break
    }else{
      repeat{
        p=readline(prompt = "This option is unavailable, please chose another one \n 1. Yes \n 2. No \n Select an option: ")
        if(p==1|p==2){break}
      }
    }
  }

Upvotes: 1

Related Questions