Intro to Programming in R
Control structures in R are essential for managing program flow, enabling decision-making and repetition. Conditionals, a key type of control structure, allow programs to execute different code blocks based on specific conditions. This unit focuses on mastering conditionals in R, including if, else, and else if statements. Understanding conditionals is crucial for writing flexible and responsive R programs. You'll learn how to use comparison operators, combine conditions with logical operators, and create nested conditionals for complex decision-making. This knowledge forms the foundation for more advanced programming techniques in R.
if
, else
, and else if
==
(equal to), !=
(not equal to), >
(greater than), and <
(less than)&
(and), |
(or), and !
(not), can be used to combine multiple conditionsif
statement is the simplest form of a conditional in Rif (condition) { code to execute if condition is true }
()
, and the code block is enclosed in curly braces {}
TRUE
, the code block is executed; otherwise, it is skippedx <- 5 if (x > 0) { print("x is positive") }
else
statement is used in conjunction with an if
statement to specify an alternative code block to execute when the if
condition is falseif (condition) { code for true condition } else { code for false condition }
else if
statement allows for testing multiple conditions in sequenceif (condition1) { code for condition1 } else if (condition2) { code for condition2 } else { code for all false conditions }
x <- 0 if (x > 0) { print("x is positive") } else if (x < 0) { print("x is negative") } else { print("x is zero") }
x <- 10 if (x > 0) { if (x %% 2 == 0) { print("x is a positive even number") } else { print("x is a positive odd number") } } else { print("x is not positive") }
&
(and) operator returns TRUE
if all conditions are true
if (condition1 & condition2) { code }
|
(or) operator returns TRUE
if at least one condition is true
if (condition1 | condition2) { code }
!
(not) operator negates a condition, returning TRUE
if the condition is false and vice versa
if (!condition) { code }
x <- 5 if (x > 0 & x %% 2 == 1) { print("x is a positive odd number") }
==
for equality instead of the assignment operator =
==
in conditional statements{}
for code blocks
else if
statements
&
instead of &&
or |
instead of ||
&
and |
for element-wise operations, and &&
and ||
for short-circuiting logical operations