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(radius){
area <- 3.14 * radius^2
return(area)
}
area_test_one <- calculate_area_of_circle(5)
print(area_test_one)
## [1] 78.5
area_test_two <- calculate_area_of_circle(10)
print(area_test_two)
## [1] 314
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_input){
if (temp_input > 30){
print('Hot')
}
else if (temp_input >= 15 & temp_input <=30){
print('Warm')
}
else {
print('Cold')
}
}
check_temp_test_one <- check_temperature(10)
## [1] "Cold"
check_temp_test_two <- check_temperature(20)
## [1] "Warm"
check_temp_test_three <- check_temperature(35)
## [1] "Hot"
cat('Test one prints:',check_temp_test_one,"\n",
'Test two prints:',check_temp_test_two,"\n",
'Test three prints:',check_temp_test_three,"\n")
## Test one prints: Cold
## Test two prints: Warm
## Test three prints: Hot
3- Write a function named sum_odd_numbers that uses a for loop to calculate the sum of all even numbers from 1 to n. The function should return the total sum.
Test the function with n = 9 and n = 39.
#Calculates the sum of all even numbers, from 1 through the input, n
sum_odd_number <- function(n){
total=0
for (i in 1:n){
if (i %% 2 == 0){
total = total + i
}
}
return(total)
}
sum_odd_number(9)
## [1] 20
sum_odd_number(39)
## [1] 380
For this section, use the built-in mtcars dataset (instead of airquality). Perform the following:
Check the structure of the dataset.
Display the summary statistics.
Check for any missing values.
Ask a simple question that can be answered with a basic function (e.g., What is the mean miles per gallon (mpg) across all cars?). Write the code and output the answer.
#mtcars
#str(mtcars)
#summary(mtcars)
#is.na(mtcars)
#What is the mean hp across all cars?
mtcars_hp_finder <- function(){
return(mean(mtcars$hp))
}
mtcars_hp_finder()
## [1] 146.6875
cat('The average horsepower across all vehicles in the mtcars dataset is:', mtcars_hp_finder())
## The average horsepower across all vehicles in the mtcars dataset is: 146.6875