Functions

1- Create a function named calculate_area_of_circle that takes one parameter, radius, representing the radius of a circle. The function should calculate and return the area using the formula:

area = đťś‹ Ă— radius^2

Test your function with at least two different radii and print the results.

# Create a function to calculate the area of a circle
calculate_area_of_circle <- function(radius) {
  area <- pi * radius^2     # formula for area of a circle
  return(area)
}

# Test the function with two different values
calculate_area_of_circle(3)
## [1] 28.27433
calculate_area_of_circle(7)
## [1] 153.938

2- Write a function called check_temperature that takes a single numeric input temp.

If temp > 30, print “Hot”

If temp >= 15 & temp <= 30, print “Warm”

Otherwise, print “Cold”

Test the function on three different values (e.g., 10, 20, 35).

# Function to check temperature range

check_temperature <- function(temp) {
if (temp > 30) {
print("Hot")
} else if (temp >= 15 & temp <= 30) {
print("Warm")
} else {
print("Cold")
}
}

# Test the function

check_temperature(10)
## [1] "Cold"
check_temperature(20)
## [1] "Warm"
check_temperature(35)
## [1] "Hot"

3- Write a function named sum_odd_numbers that uses a for loop to calculate the sum of all odd numbers from 1 to n. The function should return the total sum.

Test the function with n = 9 and n = 39.

# Function to calculate sum of all odd numbers from 1 to n

sum_odd_numbers <- function(n) {
total <- 0
for (i in 1:n) {
if (i %% 2 != 0) {      # check if the number is odd
total <- total + i
}
}
return(total)
}

# Test the function

sum_odd_numbers(9)
## [1] 25
sum_odd_numbers(39)
## [1] 400

EDA

For this section, use the built-in mtcars dataset. Perform the following:

Write a question about the dataset and answer it using functions you learned in this class. Print the output of the answer.

# Find the car with the highest MPG

highest_mpg <- mtcars[which.max(mtcars$mpg), ]
highest_mpg
##                 mpg cyl disp hp drat    wt qsec vs am gear carb
## Toyota Corolla 33.9   4 71.1 65 4.22 1.835 19.9  1  1    4    1

Answer: The car with the highest MPG is the Toyota Corolla. It has high fuel efficiency, relatively low weight, and fewer cylinders compared to other cars, which contributes to better gas mileage.