'Writing an if statement in R to find multiples of 4 or 7 but it keeps returning true for somethings thats false
I am writing an if statement comparing multiples of 4 or 7, pretty basic stuff but I am a novice programmer. Below is the function and if statements, and whenever I test 55 it returns true for some reason even though 55 is not a multiple of 4 or 7. Why is this happening? Any help appreciated, thank you so much!
isPostiveMultipleOf4Or7 <- function(n) {
if(is.character(n)) {
return(FALSE)
}
if(is.logical(n)){
return(FALSE)
}
if(abs(n)%%4 | abs(n)%%7 == 0){
return(TRUE)
}
if(abs(n)%%4 | abs(n)%%7 != 0){
return(FALSE)
}
}
55%%7 == 0
test_isPostiveMultipleOf4Or7()
isPostiveMultipleOf4Or7("hello")
isPostiveMultipleOf4Or7(28)
isPostiveMultipleOf4Or7(55)
Solution 1:[1]
You need to have the == 0
and != 0
on both sides of |
. It is returning TRUE
since abs(n)%%4
returns a value.
isPostiveMultipleOf4Or7 <- function(n) {
if(is.character(n)) {
return(FALSE)
}
if(is.logical(n)){
return(FALSE)
}
if(abs(n)%%4 == 0 | abs(n)%%7 == 0){
return(TRUE)
}
if(abs(n)%%4 != 0 | abs(n)%%7 != 0){
return(FALSE)
}
}
Test
isPostiveMultipleOf4Or7("hello")
#[1] FALSE
isPostiveMultipleOf4Or7(28)
#[1] TRUE
isPostiveMultipleOf4Or7(55)
#[1] FALSE
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | AndrewGB |