Learn/R/6. Functions
Lesson 6 of 8
Sign in

R, lesson 6

Functions

You have already called plenty of functions: cat(), sum(), as.integer(). Writing your own lets you name a piece of logic, reuse it, and test it on its own.

Defining a function

In R a function is a value like any other, created with the keyword function and stored in a variable:

width and height are parameters: placeholders that get their values when you call the function. The values you pass, 3 and 4, are called arguments.

Return values

A function gives back the value of the last expression it runs. That is why area() needs no special keyword. You can also leave early with , which is handy for special cases:

2 exercises to try what you just read.

Exercise 1

Temperature converter

Press Ctrl Enter or Check to test your code.

Exercise 2

Splitting the bill

Press Ctrl Enter or Check to test your code.

return()

Note the parentheses: return(x), not return x. A function that only prints should still be called for its effect, and it returns whatever its last line produced (often NULL from cat()), which you can ignore.

Default values and named arguments

Give a parameter a default with = in the definition. Callers can then leave it out:

When calling, you can name any argument. Named arguments may come in any order, which makes calls with several options much easier to read.

Scope: what a function can see

Variables created inside a function are local. They exist only while the function runs and do not touch variables with the same name outside:

A function can read variables from the place where it was defined (here, the top of the script), but relying on that makes code harder to follow. Pass in what the function needs as arguments and return what it produces. R does have a <<- operator that changes outer variables, but you rarely need it, and beginners are better off avoiding it.

Functions work on vectors too

Because R operations work on whole vectors, many functions you write handle a single value and a vector of values without any changes: area(c(1, 2), 5) returns 5 10.

Further reading

  • An Introduction to R, section "Writing your own functions"
  • R Language Definition, section "Functions"

Write a function to_fahrenheit(celsius) that returns celsius * 9 / 5 + 32. The input has one temperature in °C per line. For each line, print the original value and the converted value in the form C°C = F°F.

Sample input:

Sample output:

Write a function share(total, people, tip = 10) that adds a tip of tip percent to total, divides the result by people, and returns it.

The input has two or three lines: the bill total, the number of people, and optionally a tip percentage. If the third line is missing, call share() without the tip argument so the default of 10 is used. Print each person's share with exactly 2 decimals.

Sample input:

Sample output:

area <- function(width, height) {
  width * height
}

cat(area(3, 4), "\n")   # 12
safe_divide <- function(a, b) {
  if (b == 0) {
    return(NA)
  }
  a / b
}
greet <- function(name, greeting = "Hello") {
  cat(greeting, ", ", name, "!\n", sep = "")
}

greet("Ada")                     # Hello, Ada!
greet("Ada", greeting = "Hi")    # Hi, Ada!
total <- 100
add_tax <- function(price) {
  total <- price * 1.2   # a new, local total
  total
}
add_tax(10)               # 12
cat(total, "\n")         # still 100
100
-40
21.5
100°C = 212°F
-40°C = -40°F
21.5°C = 70.7°F
80
4
22.00