Practical 2

In this practical, you’ll learn to create and work with functions in R, an essential skill for writing efficient and reusable code.

Writing our first function

  1. Write a function that calculates the area of a circle, given a radius. Test your function by calling it with different inputs.
circle_area <- function(r) {
  return(pi * (r^2))
}

circle_area(5)
[1] 78.53982
circle_area(12.2)
[1] 467.5947
  1. Write a function that calculates the volume of a cone, given radius and height. The volume of a cone is defined as:

\[ \text{Volume} = \frac{1}{3}\pi r^2h \]

cone_volume <- function(r, h) {
  return((1/3) * pi * (r^2) * h)
}

cone_volume(r = 2.1, h = 5)
[1] 23.09071
  1. Update your functions to include default arguments (e.g., {r = 3}).
circle_area <- function(r = 3) {
  return(pi * (r^2))
}

circle_area()
[1] 28.27433
cone_volume <- function(r = 2, h = 5) {
  return((1/3) * pi * (r^2) * h)
}

cone_volume()
[1] 20.94395
  1. What’s the difference between these two function calls?
cone_volume(r = 2.1, h = 5)
cone_volume(2.1, 5)