using while loop with logical operators (AND and OR)
n<-NULL
acr<-NULL
while((is.numeric(n)==F) & (acr<0 ¦acr>1)){
print("enter a positive integer and the average cancellation rate you want")
try(n<-scan(what=integer(),nmax=1), silent=TRUE);
try(acr<-scan(what=double(),nmax=1), silent=TRUE)
}
I would want the users of my program to enter a positive integer which I store in "n" and the second entry which I keep in "acr" is a probability so it lies between 0 and 1. (I don't want it to be exacly 0 or 1, though it could be according to probability theory). So I want the user to keep on doing the entry until they are able to enter a positive integer for "n" and a probability value between 0 and 1 for "acr".(using while with the AND, OR operators)
However, I am having a problem with the while statement/loop. I have tried all other possibilities such as the one below, but 开发者_运维知识库it still doesn't work.
while(is.numeric(n)==F & acr<0 ¦acr>1)
AGAIN:question 2
There is a problem with what=double()
also in the scan
function, I think.
I know that, for example, 0.5 is a double data type in other programming languages but
I cannot figure it out in R(I don't know what it is called in R).
what is the difference between integer()
and double()
in R? (I am not familiar with double)
I would be highly appreciative to anyone who could come to my aid.
many thanks to all.
Isaac Owusu
This following example should work. Please be aware that is.integer()
"does not test if ‘x’ contains integer numbers! For that, use ‘round’, as in the function ‘is.wholenumber(x)’ in the examples" (see
help(is.integer)
).
For that reason, I first define a new function is.wholenumber()
.
is.wholenumber <- function(x, tol = .Machine$double.eps^0.5){
abs(x - round(x)) < tol
}
n <- NULL
acr <- NULL
stay.in.loop <- TRUE
while(stay.in.loop){
print("Please insert n and acr!")
n <- readline("Insert n: ")
acr <- readline("Insert acr: ")
n <- as.numeric(n)
acr <- as.numeric(acr)
## stay.in.loop is true IF any of the expressions is NOT TRUE
stay.in.loop <- !(is.wholenumber(n) & ((0 < acr) & (acr < 1)))
}
NULL may be a bad initialization here, as its comparison does not give a regular boolean. Since the condition is that n should be positive, try this:
n <- -2
acr <- -2
while((n<=0) | (acr<0) | (acr>1)) {
print("enter a positive integer and the average cancellation rate you want")
try(n<-scan(what=integer(),nmax=1), silent=TRUE);
try(acr<-scan(what=double(),nmax=1), silent=TRUE);
}
精彩评论