3. Functions

Learn to use built-in R functions and write your own, with live, editable R code.

R comes with hundreds of built-in functions (sum(), sd(), sort()…), and you can write your own with function(...). The last evaluated expression inside a function is what it returns.

Discuss first

Before you run the code below: water freezes at 0°C and boils at 100°C. What Fahrenheit values do you expect celsius_to_fahrenheit(0) and celsius_to_fahrenheit(100) to return?

Edit the code below if you like, then press Run Code to check your answer.

Check your understanding

Q1. What does a function return if it has no explicit return(...) call?

Q2. Fill in the blank: to apply celsius_to_fahrenheit to every element of a vector and get a vector back, you write:

(temps, celsius_to_fahrenheit)
Back to top