<- function(x, y){
fun_1 <- round(x/y^2, digits = 2)
res print(paste0("This returns:", res))
}
Functions: Exercises
These exercises are optional.
Exerise 1
Take a look at the following function:
- What does it do?
- It calculates the rounded quotient of
x
andy^2
and prints the result with some text. - It calculates the rounded quotient of
x
andy^2
but doesn’t do anything with it. - It calculates the rounded quotient of
x
andy^2
, prints this result with some text and returns only the result without any text. - It only returns the rounded quotient of
x
andy^2
without any text.
Let’s take a look:
<- fun_1(86, 1.87) out_fun_1
[1] "This returns:24.59"
out_fun_1
[1] "This returns:24.59"
Hmm, so option one seems to be correct:
- It calculates the rounded quotient of
x
andy^2
and prints the result with some text. - It calculates the rounded quotient of
x
andy^2
but doesn’t do anything with it. - It calculates the rounded quotient of
x
andy^2
, prints this result with some text and returns only the result without any text. - It only returns the rounded quotient of
x
andy^2
without any text.
Actually, this function calculates the Body Mass Index (BMI): \(\frac{weight(kg)}{height(m)^2}\). However, it doesn’t return a numeric value, but just prints the result of the calculation along with some text.
- Improve it, so it becomes clearer what it does, and it returns something more meaningful.
Assign a more informative name and more informative argument names. Use return()
to make clear what the function returns. Print a more informative statement.
<- function(kg, meter){
calc_bmi
<- round(kg/meter^2, digits = 2)
bmi
print(paste0("Your BMI is: ", bmi))
return(bmi)
}
<- calc_bmi(86, 1.87) my_bmi
[1] "Your BMI is: 24.59"
my_bmi
[1] 24.59
Here we gave the function and its arguments some more informative names. We also used the return()
function to clearly return the result of the calculation, which also makes it easy to save the output of the function in an object. Finally, we wrote a more informative printed statement.