Reputation: 38165
I want to output number of the fruits user inputs and if it is <0 or if it is greater than number I want it to break. Not sure why it is not working?!
how.many<-function(fruit, number){
string<-paste("How many",fruit,"?",sep=" ")
#cat(string)
#return(scan(string))
fruit_number<-readline(string)
stopifnot(fruit_number>number)
stopifnot(fruit_number<0)
return(fruit_number)
}
I should output 4 when the number is 4 but it breaks. > how.many("banana",5)
How many banana ?0
Error: fruit_number > number is not TRUE
> how.many("banana",5)
How many banana ?9
Error: fruit_number < 0 is not TRUE
> how.many("banana",5)
How many banana ?4
Error: fruit_number > number is not TRUE
Upvotes: 1
Views: 258
Reputation: 42659
Your tests are reversed. You need to specify a TRUE value to not stop (as it says, stopifnot).
how.many<-function(fruit, number){
string<-paste("How many",fruit,"?",sep=" ")
#cat(string)
#return(scan(string))
fruit_number<-readline(string)
stopifnot(fruit_number<=number)
stopifnot(fruit_number>=0)
return(fruit_number)
}
> how.many("banana", 5)
How many banana ?9
Error: fruit_number <= number is not TRUE
> how.many("banana", 5)
How many banana ?4
[1] "4"
Upvotes: 2
Reputation: 838
stopifnot
actually means what it says: "stop if not(...)". And (4 > 5) is not true. So it stops. You want the opposite signs.
Upvotes: 1