获得1或-1

时间:2017-06-30 11:42:50

标签: r function

我想从用户获得-1或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)){
    if(B.Y!=-1|BY!=1)
    return(readB.Y())
}
# to ensure the input is integer
return(as.integer(B.Y))
}
BY<-readB.Y()

谢谢。

1 个答案:

答案 0 :(得分:4)

您需要更改条件以允许负数并排除不同于-1和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))
}
}

您可以进一步简化您的条件

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))
}
}

<强>示例:

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