Functions

Functions

Almost everything you do in R happens by calling a function. A function takes some input, does something with it, and returns a result. You call a function by typing its name, followed by parentheses that hold the input:

sqrt(16)
round(3.14159)

If you have used Python, this will look familiar: np.sqrt(16) becomes sqrt(16). Everyday maths and statistics functions are built into R, so there is nothing to import first.

Three things are worth knowing from the start:

  • Typing a function’s name without parentheses shows you the code the function runs, rather than running it.
  • ?name opens the function’s help page.
  • R ignores anything after a # on a line, so you can use # to write comments.

Run the chunk below, then change it to round pi (which is built into R).

Run a function

Can you use the sqrt() function in the chunk below to compute the square root of 962?

sqrt(962)

Code

Use the code chunk below to examine the code that sqrt() runs.

sqrt

Good job! sqrt immediately triggers a low level algorithm optimized for performance, so there is not much code to see.

lm

Compare the code in sqrt() to the code in another R function, lm(). Examine lm()’s code body in the chunk below.

lm

Help pages

Wow! lm() runs a lot of code. What does it do? Open the help page for lm() in the chunk below and find out.

?lm

Good job! lm() is R’s function for fitting basic linear models. No wonder it runs so much code.

Code comments

What do you think the chunk below will return? Run it and see. The result should be nothing. R will not run anything on a line after a # symbol. This is useful because it lets you write human readable comments in your code: just place the comments after a #. Now delete the # and re-run the chunk. You should see a result.

sqrt(962)

Next topic