Reputation: 47
I want to get from the user either -1 or 1, but the attached function allows the user to input any value. How can it be modified?
readB.Y<-function(){
#B.Y is a storage variable that will be used later
B.Y<-readline(prompt = "ENTER THE NUMBER OF B.Y:")
# if the input is not integer, ask again for integer input
if(!grepl("^[0-9]+$",B.Y)){
if(B.Y!=-1|BY!=1)
return(readB.Y())
}
# to ensure the input is integer
return(as.integer(B.Y))
}
BY<-readB.Y()
Thank you.
Upvotes: 0
Views: 86
Reputation: 24074
You need to change your condition to allow negative numbers and exclude numbers that are different from -1 and 1:
readB.Y <- function(){
#B.Y is a storage variable that will be used later
B.Y<-readline(prompt = "ENTER THE NUMBER OF B.Y:")
# if the input is not integer, ask again for integer input
if((!grepl("^-?[0-9]+$",B.Y)) | (!(B.Y %in% c(-1, 1)))){ # -? means that it can or not have a minus sign
return(readB.Y())
} else {
# to ensure the input is integer
return(as.integer(B.Y))
}
}
You can further simplify your condition to
readB.Y <- function(){
#B.Y is a storage variable that will be used later
B.Y<-readline(prompt = "ENTER THE NUMBER OF B.Y:")
# if the input is not integer, ask again for integer input
if(!grepl("^-?1$", B.Y)){ # what is enter can only be 1 or -1
return(readB.Y())
} else {
# to ensure the input is integer
return(as.integer(B.Y))
}
}
Examples:
BY<-readB.Y()
#ENTER THE NUMBER OF B.Y:99
#ENTER THE NUMBER OF B.Y:2
#ENTER THE NUMBER OF B.Y:-1
BY<-readB.Y()
#ENTER THE NUMBER OF B.Y:6
#ENTER THE NUMBER OF B.Y:1
Upvotes: 4