Try It

Reading about functions only gets you so far. The fastest way to really understand them is to call a lot of them and watch what happens. This page is entirely hands-on.

Calling Your First Functions

Do: run each of the following function calls one at a time. For each one, pause and see what it prints before moving to the next line.

Practice: Change the Input

Now it’s your turn. In the editor below, call sum(), mean(), and length() on the vector c(10, 20, 30, 40, 50).

sum(c(10, 20, 30, 40, 50))
[1] 150
mean(c(10, 20, 30, 40, 50))
[1] 30
length(c(10, 20, 30, 40, 50))
[1] 5

Same Function, Different Input

One of the most important habits to build is changing the input to a function you already know, just to see what happens. This is one of the best ways to build intuition for how a function behaves.

Practice: Predict, Then Run

Predict what each of the following will print, before running the code. Each line calls the same function, round(), with a different input.

round(3.14159)
round(3.14159, 2)
round(7)
round(-2.5)
round(3.14159)
[1] 3
round(3.14159, 2)
[1] 3.14
round(7)
[1] 7
round(-2.5)
[1] -2

Changing the first input changes what gets rounded, while changing the second input (when we provide one) changes how precisely it gets rounded. Notice that round(7) still works even though 7 is already a whole number. R doesn’t complain, it just returns 7. We’ll formally introduce these “extra” inputs, called arguments, on the next page.

Quick Check

Using the editor below, call sqrt() on three different numbers of your choosing. What pattern do you notice about how the output changes as your input changes?

Back to top