Intro to Coding

Part 2: Functions and Packages

Part 1 | Part 2 | Part 3 | Part 4

Functions: the workhorse of programming

The basics

Functions are like little machines that do specialized things for you. R comes with some of these machines built-in and ready to go. You can also build your own machines from scratch! But most importantly, you can use machines that other people have built by loading “libraries” of these machines!

Under the hood, functions are just code. Code cleverly written to do something useful. So when you load a library, you’re just borrowing code. Usually it gives you new functions, new variables, other new things that R doesn’t do out of the box.

Typically, a function is given some inputs, does something with them, and gives an output. It’s the same concept as functions in math (e.g., \(f(x)\)) Perhaps this visual will help:

A diagram with the input x pointing into a box labelled function f and then an arrow pointing out of the box to the output y.
Figure 1: A mathematical function as a box with inputs and outputs.

Functions built-in to R

R comes with some native functions, ready for you to use. An example we’ve already seen is sum. To use sum, you type its name, then an open parenthesis (, then all the inputs you want to give it (separated by commas!) then a closing parenthesis ). Have a look:

Here we have used the function sum and gave it three inputs: 4, 5, and 6. The output was 15.

Proper terminology:: In programming, we say that we “called” sum and “passed” it three “arguments”: 4, 5, and 6. Then it “returned” the output, 15.

Try writing a sentence like the one above for the line of code below. (sqrt is a function that takes the square root of a number)

Reveal answer

We called sqrt and passed it one argument: 16. It returned 4.

sum is unusual in that you can give it as many inputs as you want; we gave it 4, 5, and 6 above, but we could have given it more numbers. By contrast, most functions expect a specific number of inputs – no more, no less. For example, sqrt expects exactly one input. If you pass too few or too many arguments, it will complain. The code below will throw an error (run it):

In this case the error message is actually pretty intuitive. Always read your error messages; even if some of it is gibberish, some will offer you clues.

Using functions in real code

You can use functions in the middle of your commands. R will run the little machines and replace that part of the code with the answer. Like so:

Essentially, R sees the function, runs sqrt(4) first, gets the result (2) and fills that into the command, becoming 7 + 2.

Another example:

Nesting functions: if you follow the logic above closely, you can guess how this code might work:

Remember, the stuff to the right of the <- is resolved first. It wants to add 3 to something… but that something is not yet a number. It sees the sqrt function, which also expects a number. But what’s inside sqrt() is also not a number yet, it’s sum(4, 5, 7). R sees this function and knows what to do with it. Then everythign else can unroll, from the inside out:

  1. We start with the line x <- 3 + sqrt(sum(4, 5, 7))
  2. The inner-most bit, sum(4, 5, 7), is run and replaced with the result, 16
  3. Now we have the line, x <- 3 + sqrt(16)
  4. sqrt(16) is resolved next (result: 4), leaving us x <- 3 + 4
  5. It does the math on the right, bringing us to x <- 7
  6. A new variable x is created that refers to the value 7.
  7. The next line is a new command: x + 1
  8. R recognizes x as a variable and replaces it with its value, 7
  9. 7 + 1 is computed and shown.

Libraries of code (aka “packages”)

Basics

At the top of every R file you’ll work on, you’ll write special lines of code that look like: library(tidyverse). These are ways to bring in more functions than R natively knows, functions that other people have written to do useful things. Coding is all about not reinventing the wheel, and there are thousands of libraries out there. In this class we only focus on a few popular ones.

Consider this problem: R does not know how to extract data from an excel spreadsheet. There is no function like read_excel in R. If you have some accounting data in a spreadsheet called budget.xls, you couldn’t do this:

read_excel("budget.xls")

This would throw an error. Regular old R has no idea what read_excel means. So if you want to load data from excel files for your work, you either you have to figure out how to do that in code that you write yourself, from scratch… or you can rely on someone who’s already solved that problem for you.

And there is. There’s a library called readxl created by someone in the R community. It’s freely available for everyone to use (most libraries are). When readxl is loaded, it teaches R a bunch of new functions, including one called read_excel.

This code would work:

library(readxl)
read_excel("budget.xls")

Once you have run the library(readxl) once, you don’t have to do it again. For the rest of your work, even in other code cells, read_excel will still work. So after running the cell above, later you could do just:

read_excel("new_budget.xls")

R has “loaded” all the knowledge from the readxl library into its working memory, and will remember it until you reboot R.

This class’s libraries

For almost everything you do in this class, you’ll need the two libraries: tidyverse and stat20data. In other words, the FIRST cell of code in every file you write should look like this:

Loading tidyverse brings in a whole arsenal of useful tools for data science, which you’ll get to know over the next few lessons. The stat20data library gives you access to some pre-made datasets, stored as variables. For example, the penguins dataset becomes available as a variable once you load stat20data.

Below you can see this in action. We are using another new function, slice_sample, which was loaded as part of tidyverse. The code below will get us the first 5 rows of the penguins dataset.

Try running the cell above. If you get an error, it’s because you didn’t run the previous cell that actually does the library loading! You haven’t taught R about penguins or slice_sample yet, and they aren’t native words in R. Run the previous cell that loads the libraries, then try the the cell above again. Now it will work. You’re going to run into this exact problem when you do your work. Now you know what to do.

The takeaway is that libraries bring in new functionality. They are your best friend.