Functions: Exercises

Note

These exercises are optional.

Exerise 1

Take a look at the following function:

fun_1 <- function(x, y){ 
 res <- round(x/y^2, digits = 2)
 print(paste0("This returns:", res))
}
  1. What does it do?
  • It calculates the rounded quotient of x and y^2 and prints the result with some text.
  • It calculates the rounded quotient of x and y^2 but doesn’t do anything with it.
  • It calculates the rounded quotient of x and y^2, prints this result with some text and returns only the result without any text.
  • It only returns the rounded quotient of x and y^2 without any text.

Let’s take a look:

out_fun_1 <- fun_1(86, 1.87)
[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 and y^2 and prints the result with some text.
  • It calculates the rounded quotient of x and y^2 but doesn’t do anything with it.
  • It calculates the rounded quotient of x and y^2, prints this result with some text and returns only the result without any text.
  • It only returns the rounded quotient of x and y^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.

  1. 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.

calc_bmi <- function(kg, meter){ 
 
  bmi <- round(kg/meter^2, digits = 2)
 
  print(paste0("Your BMI is: ", bmi))
 
  return(bmi)
}

my_bmi <- calc_bmi(86, 1.87)
[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.