Using IF ELSE in R

Basics:

x <- 5
if (x == 5){ 
   print("x = 5")
   }
#response: "x = 5"

if (x == 6){
   print("x = 5")
}
#no response

If Else

if (x == 5){
   print("x = 5")
 }else{
   print("x doesn't equal 5")

 }
#response "x = 5"

if (x == 6){
  print("x = 6")

}else{
  print("x doesn't equal 6")
}
#response: "x doesn't equal 6"

To make a IF NOT statement add the ! function in the mix

x <- 5
if (!(x == 5)){ 
   print("x does not = 5")
   }
#no response

if (!(x == 6)){ 
   print("x does not = 6")
   }
#response: "x does not = 6"

For numbers you can do the same thing with the not equal sign

x <- 5
if (x != 6){ 
   print("x does not = 6")
   }
#return "x does not = 6"

Make a chain of if statements with if, else if statements. (like python’s elif)

x <- 5
if (x < 5){ 
   print("x is less than 5")
   }else if(x > 5){
     print("x is more than 5")
   }else if(x == 5){
     print ("x is equal to 5")
   }else {
     print ("x is not a number")
   }
#return: "x is equal to 5"

Also look at elseif()

ifelse returns a value with the same shape as test which is filled with elements selected from either yes or no depending on whether the element of test is TRUE or FALSE.

x <- 5
print(ifelse(x==5, 'x is equal to 5', NA))
# "x is equal to 5"

print(ifelse(x==6, 'x is equal to 5', 'x is not equal to 5'))
# "x is not equal to 5"

ifelse(x == 5, print('x is equal to 5'), print('x is not equal to 5'))
# "x is equal to 5"
# "x is equal to 5"

y <- 5
ifelse(y == 5, print('y is equal to 5'), print('y is not equal to 5'))
# "y is not equal to 5"
# "y is not equal to 5"

NOTE: ifelse() strips attributes

https://rdrr.io/r/base/ifelse.html

For Tidyverse look at if_else()

https://dplyr.tidyverse.org/reference/if_else.html