R - Decision Making: A Beginner's Guide
Hello, future R programmers! I'm thrilled to be your guide on this exciting journey into the world of decision making in R. As someone who's been teaching computer science for years, I've seen countless students light up when they grasp these concepts. So, let's dive in and make some decisions!
What is Decision Making in Programming?
Before we jump into R specifics, let's talk about what decision making means in programming. Imagine you're at an ice cream shop. You don't just grab the first flavor you see, right? You make a decision based on your preferences. Programming is similar - we want our code to make choices based on certain conditions.
Basic Decision Making in R: The if
Statement
The Syntax
Let's start with the most fundamental decision-making tool in R: the if
statement. Here's its basic structure:
if (condition) {
# Code to execute if the condition is TRUE
}
A Simple Example
Let's say we want to check if a number is positive. Here's how we'd do it:
x <- 5
if (x > 0) {
print("x is positive")
}
When you run this code, you'll see "x is positive" printed. Why? Because 5 is indeed greater than 0, so the condition x > 0
is TRUE.
Adding an else
Clause
But what if we want to do something when the condition is FALSE? That's where the else
clause comes in:
x <- -3
if (x > 0) {
print("x is positive")
} else {
print("x is not positive")
}
Run this, and you'll see "x is not positive". The else
clause gives us a way to handle the FALSE case.
More Complex Decisions: else if
Sometimes, life (and programming) isn't just black and white. We might need to check multiple conditions. Enter else if
:
x <- 0
if (x > 0) {
print("x is positive")
} else if (x < 0) {
print("x is negative")
} else {
print("x is zero")
}
This code checks if x is positive, negative, or zero. It's like a choose-your-own-adventure book for numbers!
The Mighty switch
Statement
When you have multiple specific cases to check, the switch
statement can be your best friend. It's like a vending machine for code execution:
day <- "Monday"
mood <- switch(day,
"Monday" = "Need coffee",
"Friday" = "TGIF!",
"It's a regular day"
)
print(mood)
This will print "Need coffee". The switch
statement matches the value of day
with the options and returns the corresponding value.
Conditional Execution with ifelse()
R has a nifty function called ifelse()
that combines an if-else statement into a single line:
x <- 10
result <- ifelse(x > 5, "Greater than 5", "Not greater than 5")
print(result)
This will print "Greater than 5". The ifelse()
function is great for quick, simple conditions.
Comparison Operators: The Building Blocks of Conditions
To make decisions, we need to compare values. Here are the comparison operators in R:
Operator | Meaning |
---|---|
< |
Less than |
> |
Greater than |
<= |
Less than or equal to |
>= |
Greater than or equal to |
== |
Equal to |
!= |
Not equal to |
For example:
a <- 5
b <- 10
print(a < b) # TRUE
print(a == b) # FALSE
Logical Operators: Combining Conditions
Sometimes, we need to check multiple conditions at once. That's where logical operators come in:
Operator | Meaning |
---|---|
& |
AND |
| |
OR |
! |
NOT |
Here's how you might use them:
age <- 25
has_license <- TRUE
if (age >= 18 & has_license) {
print("You can drive")
} else {
print("You can't drive")
}
This checks if someone is both of legal age AND has a license before allowing them to drive.
Putting It All Together: A Real-World Example
Let's create a simple grading system:
grade_student <- function(score) {
if (score >= 90) {
return("A")
} else if (score >= 80) {
return("B")
} else if (score >= 70) {
return("C")
} else if (score >= 60) {
return("D")
} else {
return("F")
}
}
# Let's test our function
students <- c("Alice", "Bob", "Charlie")
scores <- c(95, 82, 65)
for (i in 1:length(students)) {
grade <- grade_student(scores[i])
print(paste(students[i], "got a grade of", grade))
}
This script defines a function to assign letter grades based on numerical scores, then applies it to a list of students.
Conclusion
Congratulations! You've just taken your first steps into the world of decision making in R. Remember, like learning any new skill, practice makes perfect. Don't be afraid to experiment with these concepts - that's how real learning happens!
In my years of teaching, I've found that students who play around with code, break things, and then fix them again tend to understand the concepts much more deeply. So go forth, make decisions (in your code), and have fun!
Credits: Image by storyset