Hands-On Exercises
These exercises are designed to reinforce:
- Writing custom functions
- Using conditional logic
- Writing loops
- Using apply functions
Work through them in order.
Exercise #1
Create a Custom Function with Conditions
Write a function called grade_score() that:
- Takes one numeric argument called
score - Returns:
"A"if score ≥ 90
"B"if score ≥ 80
"C"if score ≥ 70
"F"otherwise
- Uses
if,else if, andelse - Stops with an error if the score is less than 0 or greater than 100
Example behavior:
grade_score(95) # "A"
grade_score(72) # "C"
grade_score(150) # errorBonus:
- Add a default argument so the maximum possible score is 100.
- Modify the function to return both the letter grade and a message in a list.
Exercise #2
Write a Loop with a Condition
Create a for loop that:
- Iterates through numbers 1 to 20
- Prints the number only if:
- The number is divisible by 3
- AND the number is greater than 10
- The number is divisible by 3
Expected output:
12
15
18Bonus:
- Modify the loop to print:
"<number> is divisible by 3"instead of just the number
- Rewrite the solution using
ifelse() - Rewrite the solution using
sapply()
Optional Challenge (Advanced)
Apply Function Practice
- Create a matrix with numbers 1 to 25 arranged in 5 rows.
- Use:
apply()to compute row meansapply()to compute column sums
- Compare your results to:
rowMeans()colSums()
Extra Challenge:
- Create a list of 3 numeric vectors.
- Use
lapply()to compute the standard deviation of each. - Then use
sapply()and observe the difference in output.