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
- 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)
- 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)
- Update your functions to include default arguments (e.g.,
{r = 3}).
circle_area <- function(r = 3) {
return(pi * (r^2))
}
circle_area()
cone_volume <- function(r = 2, h = 5) {
return((1/3) * pi * (r^2) * h)
}
cone_volume()
- What’s the difference between these two function calls?
cone_volume(r = 2.1, h = 5)
cone_volume(2.1, 5)