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.
calculate_area_of_circle <- function(r) {
pi * r ^ 2
}
print(calculate_area_of_circle(1))
## [1] 3.141593
print(calculate_area_of_circle(2))
## [1] 12.56637
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).
check_temperature <- function(temp) {
if(temp > 30) {
print("Hot")
} else if(temp >=15) {
print("Warm")
} else {
print("Cold")
}
}
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.
sum_odd_numbers <- function(n) {
odds <- seq(1, n, 2)
result <- 0
for(o in odds) {
result <- result + o
}
result
}
sum_odd_numbers(9)
## [1] 25
sum_odd_numbers(39)
## [1] 400
For this section, use the built-in mtcars dataset. Perform the following:
Check the structure of the dataset.
Display the summary statistics.
Check for any missing values.
Write a question about the dataset and answer it using functions you learned in this class. Print the output of the answer.
Question: Is mpg correlated with
qsec (quater mile time)?
head(mtcars)
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
## Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
print(summary(mtcars$mpg))
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 10.40 15.43 19.20 20.09 22.80 33.90
print(summary(mtcars$qsec))
## Min. 1st Qu. Median Mean 3rd Qu. Max.
## 14.50 16.89 17.71 17.85 18.90 22.90
plot(mtcars$mpg,mtcars$qsec)
print(colSums(is.na(mtcars)))
## mpg cyl disp hp drat wt qsec vs am gear carb
## 0 0 0 0 0 0 0 0 0 0 0
cor_matrix <- cor(
mtcars |>
select(mpg,qsec), use = "complete.obs")
print(cor_matrix)
## mpg qsec
## mpg 1.000000 0.418684
## qsec 0.418684 1.000000
Yes, MPG is correlated with the quater mile time— more efficient cars are slower to complete the quarter mile, with an R = 0.4186.