Lesson 4 of 8 · 8 min

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

  1. bmi(weight, height): weight divided by height squared, rounded to 1 decimal.
  2. percent_change(old, new, digits = 1): the percentage change from old to new, rounded to digits decimals.
script.R
bmi <- function(weight, height) {
}

percent_change <- function(old, new) {
}

print(bmi(70, 1.75))

R 4.5 runs right here in your browser. The first run downloads about 25 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…