Writing functions
Functions are created with function and stored in a variable like any other value:
area <- function(width, height) {
width * height
}
area(3, 4) # [1] 12
The value of the last expression is returned automatically. (return(x) also works, and is useful to leave early.)
Default arguments
greet <- function(name, greeting = "Hello") {
paste0(greeting, ", ", name, "!")
}
greet("Ana") # "Hello, Ana!"
greet("Ana", greeting = "Mhoro") # "Mhoro, Ana!"
You can pass arguments by name in any order, which makes calls with many options readable.
Functions and vectors
If the body uses vectorised operations, your function automatically works on whole vectors:
to_fahrenheit <- function(c) c * 9 / 5 + 32
to_fahrenheit(c(0, 25, 100)) # 32 77 212
A one-line function can drop the braces, as above. paste0 joins text with nothing in between; paste joins with spaces.
Your task
bmi(weight, height): weight divided by height squared, rounded to 1 decimal.percent_change(old, new, digits = 1): the percentage change fromoldtonew, rounded todigitsdecimals.