Hands-On Exercises

These exercises are designed to reinforce:

Work through them in order.

Exercise #1

Create a Custom Function with Conditions

Write a function called grade_score() that:

  1. Takes one numeric argument called score
  2. Returns:
    • "A" if score ≥ 90
    • "B" if score ≥ 80
    • "C" if score ≥ 70
    • "F" otherwise
  3. Uses if, else if, and else
  4. 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)  # error

Bonus:

  • 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:

  1. Iterates through numbers 1 to 20
  2. Prints the number only if:
    • The number is divisible by 3
    • AND the number is greater than 10

Expected output:

12
15
18

Bonus:

  • 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

  1. Create a matrix with numbers 1 to 25 arranged in 5 rows.
  2. Use:
    • apply() to compute row means
    • apply() to compute column sums
  3. 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.