x <- 5
y <- 12
participants <- 1006 Basic operations, custom functions, and packages
6.1 Overview
This chapter is the longest in Section 1. It is also the chapter where the value of working in R, as opposed to working in SPSS or Excel, becomes most concrete. The chapter is organized in four parts:
- Basic operations: assignment, arithmetic, and the small set of summary functions you will use most often (
mean,sd,min,max,median). - A first look at custom functions: how you would package a few of those operations into a single named operation, illustrated with a deliberately simple example using
ifandelse. - A substantive example: a survey dataset whose variables have been distorted by a software bug, walked through three times: manually, with a function applied repeatedly, and with a function applied in a single line. This is the example that shows what coding actually buys you.
- Packages: what they are, how to install and load them, and how to find documentation. Most of the functions you will use in your career are in packages, not in base R.
A note before we begin. We introduce custom functions in this chapter only for illustration. In the rest of Section 1 and the early sections that follow, you will not need to write your own functions. There are tens of thousands of functions already written by other people, and most of your learning curve will be about finding them and using them. We will return to writing your own functions much later in the book, once you are comfortable using existing ones.
6.2 Basic operations
6.2.1 Assignment
You assign a value to a name with the arrow <-:
The arrow is read “gets”: “x gets 5.” You can also use =, but <- is the convention in R, and it removes ambiguity in places where = has another meaning (notably inside function calls, where = is used for named arguments).
6.2.2 Arithmetic
R supports the usual arithmetic operators:
x + y # addition: 17
x - y # subtraction: -7
x * y # multiplication: 60
x / y # division: 0.4166667
x^2 # exponentiation: 25
y %% 5 # remainder ("modulo"): 2
y %/% 5 # integer division: 2These work on vectors as well as on single values. When applied to a vector, the operation is done element-wise:
ages <- c(19, 22, 21, 25, 18, 30, 27)
ages + 10
# returns c(29, 32, 31, 35, 28, 40, 37)
ages / 2
# returns c(9.5, 11.0, 10.5, 12.5, 9.0, 15.0, 13.5)When two vectors of the same length are combined, the operation is applied element-wise:
v1 <- c(1, 2, 3, 4)
v2 <- c(10, 20, 30, 40)
v1 + v2
# returns c(11, 22, 33, 44)6.2.3 Summary functions
The functions you will use most often when you first look at a vector of numbers are:
sum(ages) # total
mean(ages) # arithmetic mean
median(ages) # median
min(ages) # smallest value
max(ages) # largest value
range(ages) # min and max returned together as a vector of length 2
sd(ages) # standard deviation (using n - 1)
var(ages) # variance (using n - 1)
length(ages) # number of elementsAnd the very useful catch-all:
summary(ages)
# returns Min., 1st Qu., Median, Mean, 3rd Qu., Max.summary() is type-aware. On a numeric vector you get the six-number summary above. On a logical vector you get counts of TRUE and FALSE. On a data frame, you get a one-column summary for each column.
A single practical caveat: if any value in the vector is missing (NA), most of these functions return NA by default. To compute over the non-missing values only, set the na.rm argument to TRUE:
ages_with_na <- c(19, 22, NA, 25, 18, 30, 27)
mean(ages_with_na) # returns NA
mean(ages_with_na, na.rm = TRUE) # returns 23.5You will encounter na.rm = TRUE constantly in real data analysis, because real data has missing values.
6.3 A first look at custom functions
Suppose you frequently want to look at five summaries of a vector at once: the mean, the standard deviation, the median, the minimum, and the maximum. You could write the five lines every time:
mean(ages)
sd(ages)
median(ages)
min(ages)
max(ages)This is tedious. A custom function lets you bundle those lines into one named operation.
Here is the simplest possible version:
quick_summary <- function(x) {
cat("Mean: ", mean(x), "\n")
cat("SD: ", sd(x), "\n")
cat("Median: ", median(x), "\n")
cat("Min: ", min(x), "\n")
cat("Max: ", max(x), "\n")
}Read this carefully. The structure of every function definition in R is the same:
function_name <- function(arguments) {
body
}
function_name <- function(...) says “create a function and give it a name.” The arguments listed in the parentheses are the inputs. The body, between the curly braces, is the code that runs when the function is called. (cat() is a small function that prints text to the Console; "\n" is a newline character that puts the next item on its own line.)
To use the new function, call it like any other function:
quick_summary(ages)The function runs its body on ages, prints five lines, and returns nothing further.
We can make the function slightly more careful by adding a check. Suppose we want it to refuse non-numeric input rather than producing a confusing error from mean(). We can use if and else:
quick_summary <- function(x) {
if (!is.numeric(x)) {
cat("Input is not numeric; quick_summary cannot run.\n")
} else {
cat("Mean: ", mean(x), "\n")
cat("SD: ", sd(x), "\n")
cat("Median: ", median(x), "\n")
cat("Min: ", min(x), "\n")
cat("Max: ", max(x), "\n")
}
}is.numeric(x) returns TRUE if x is numeric and FALSE otherwise. !is.numeric(x) reverses this; the ! means “not.” So the if statement is read: “if x is not numeric, print a warning; else, print the five summaries.”
You now have a tiny function with a guard clause. Call it on a numeric vector and you get the summaries; call it on a string vector and you get the warning:
quick_summary(ages)
quick_summary(c("a", "b", "c"))This is intentionally a small example. We are not yet using any of the more flexible tools R has for writing functions; in particular, we are not using the “apply” family of functions, which we will introduce much later. For now, the goal is for you to recognize the structure of a function definition when you see it, not to write your own.
6.4 A substantive example: correcting many distorted variables
We now turn to the example that motivates the chapter. The example is realistic: at some point in your career you will encounter a dataset where a software bug, a coding mistake, or an unusual recoding scheme has left many variables in a slightly wrong form, and you will need to fix them.
6.4.1 The setup
Suppose you have run a survey on attitudes toward climate policy. The survey was administered through an online platform that, due to a bug in its export function, has shifted every Likert-scale response upward by 2 and multiplied it by 0.5. So the values you see on disk are not the raw responses but (raw + 2) * 0.5. To recover the raw responses, you need to apply the inverse transformation: raw = value / 0.5 - 2, i.e., raw = value * 2 - 2.
Your dataset has many such variables: ten Likert items measuring attitudes (item1 through item10), and several demographic variables that are not affected. The question is how to apply the correction to the ten Likert variables while leaving the rest alone.
We will work through three approaches: manual line-by-line correction, a custom function applied to each variable, and a custom function applied to all variables in one line. The first two are introduced specifically so that you can see how the third improves on them.
For the example we will use a small fake dataset:
survey <- data.frame(
id = 1:5,
age = c(34, 27, 45, 39, 22),
item1 = c(2.5, 3.0, 1.5, 2.0, 3.5),
item2 = c(2.0, 2.5, 2.5, 3.0, 1.5),
item3 = c(3.0, 2.0, 2.0, 2.5, 2.5),
item4 = c(2.5, 2.5, 3.0, 1.5, 2.0),
item5 = c(2.0, 3.0, 2.0, 2.5, 2.5),
item6 = c(3.0, 2.5, 1.5, 3.0, 2.0),
item7 = c(2.5, 2.0, 2.5, 2.5, 3.0),
item8 = c(2.0, 2.5, 3.0, 2.0, 1.5),
item9 = c(3.0, 2.5, 2.0, 3.0, 2.5),
item10 = c(2.5, 3.0, 2.5, 1.5, 2.0)
)6.4.2 Approach 1: manual correction, one line per variable
The naive approach is to write out the correction for each variable in turn:
survey$item1 <- survey$item1 * 2 - 2
survey$item2 <- survey$item2 * 2 - 2
survey$item3 <- survey$item3 * 2 - 2
survey$item4 <- survey$item4 * 2 - 2
survey$item5 <- survey$item5 * 2 - 2
survey$item6 <- survey$item6 * 2 - 2
survey$item7 <- survey$item7 * 2 - 2
survey$item8 <- survey$item8 * 2 - 2
survey$item9 <- survey$item9 * 2 - 2
survey$item10 <- survey$item10 * 2 - 2This works. Run it and the ten columns are now in their corrected form. Notice three things about it.
First, this is roughly what you would have to do in SPSS or Excel: a separate operation for each column, one click or one formula per variable. With ten items it is bearable; with sixty it is painful and error-prone.
Second, if the correction itself is wrong, you have to fix it in ten places. Imagine you discover that the right inverse is actually value * 2 - 4, not value * 2 - 2. Now you have ten lines to edit, and if you miss one you will quietly use the wrong correction on one variable for the rest of the project.
Third, the code is hard to read. The pattern repeats ten times; the only differences are the variable names. You have to look closely to verify that all ten lines really do the same thing and that none of them has a typo.
6.4.3 Approach 2: a custom function applied to each variable
A small improvement is to write the correction once, as a function, and then apply that function to each variable:
correct_value <- function(x) {
x * 2 - 2
}
survey$item1 <- correct_value(survey$item1)
survey$item2 <- correct_value(survey$item2)
survey$item3 <- correct_value(survey$item3)
survey$item4 <- correct_value(survey$item4)
survey$item5 <- correct_value(survey$item5)
survey$item6 <- correct_value(survey$item6)
survey$item7 <- correct_value(survey$item7)
survey$item8 <- correct_value(survey$item8)
survey$item9 <- correct_value(survey$item9)
survey$item10 <- correct_value(survey$item10)This is better. The correction itself is now defined once: if it is wrong, you fix one place. The ten lines that follow are clearly doing the same thing to each variable; a typo in the formula is impossible because the formula is no longer being typed ten times.
But the ten repetitive lines are still present. If you discover that the correction should not be applied to item3 after all, you have to remove or modify line three. If you have sixty items, this section is sixty lines long. The error-detection benefit is real, but the scaling benefit is not.
6.4.4 Approach 3: a custom function applied to all variables at once
What follows is shown for illustration only. The code uses a few features (lapply(), indexing a data frame with a vector of column names, replacing several columns at once) that we will not introduce properly until later in the book. You are not expected to write code like this yourself yet. The reason for showing it now is so that you can see what becomes possible with the full toolkit, not so that you can immediately reproduce it. Read the next few paragraphs once for the comparison, then move on.
The full benefit appears when you apply the function to all relevant variables at once.
correct_value <- function(x) {
x * 2 - 2
}
likert_columns <- c("item1", "item2", "item3", "item4", "item5",
"item6", "item7", "item8", "item9", "item10")
survey[likert_columns] <- lapply(survey[likert_columns], correct_value)The function definition is the same one we wrote in Approach 2. The two lines that follow do the work: the first lists the columns the correction applies to, and the second applies the function to all of them in one go. With sixty Likert variables instead of ten, only the column list grows; the line that applies the function stays exactly as it is.
To make sense of the second line, three pieces of new syntax are worth unpacking.
Indexing a data frame with a vector of column names. In Chapter 5 we used survey$item1 to pull out a single column by name, and survey[, 2] to pull out a single column by position. There is also a third form: when you put a vector of names between the square brackets, R returns a smaller data frame containing just the columns whose names appear in that vector. So survey[likert_columns] returns a sub-data-frame with the ten Likert columns and nothing else, in the order listed. (You can also write this as survey[, likert_columns] with the comma; both are equivalent for column selection.)
lapply(). lapply() is a function that takes a list (or a data frame, which R treats internally as a list of columns) and a function, and applies that function to each element in turn. lapply(survey[likert_columns], correct_value) therefore calls correct_value() once on each of the ten Likert columns, and bundles the ten resulting vectors back into a list.
Assigning back into the data frame. The line begins survey[likert_columns] <-, which says: take the ten columns named in likert_columns, and replace them with whatever is on the right-hand side. The right-hand side is the list of ten corrected vectors produced by lapply(). The assignment overwrites the original ten columns with the corrected ones, in place. The other columns of survey (like id and age) are not touched.
You do not need to fully understand any of this yet. We will return to it carefully later. For now, what matters is the comparison.
Three things have improved.
First, scaling. With sixty Likert variables instead of ten, this code stays at two lines. You add the new variable names to likert_columns and you are done.
Second, correction. If the correction formula is wrong, you fix it in correct_value(), in one place. The line that applies it does not change.
Third, error detection. Read the two lines aloud: “the Likert columns are item1 through item10; apply correct_value to all of them.” The intent is clear in two lines, in a way that ten or sixty repeated lines obscure.
6.4.5 What this would have looked like in SPSS or Excel
Compare what we just did with what you would have done in SPSS or Excel.
In SPSS, with the menus, you would have used Transform > Compute Variable, ten times, once per variable. With syntax, you would have written ten compute commands. Either way, ten operations.
In Excel, you would have inserted ten new columns next to the originals, written the formula in each, copied it down, and then either replaced the originals with the corrected versions or kept both side by side (cluttering the spreadsheet).
In both cases, if the correction formula was later found to be wrong, you would re-do all ten operations. In neither case would there be a written record, in code, of what was done. A reviewer asking “exactly how did you correct these variables?” would receive an answer that depends on your memory of the menu sequence.
The R version is shorter to write, faster to update, and self-documenting. This is the moment in the book where the value of coding becomes concrete. It is not about typing fewer characters; it is about the operation being re-runnable, inspectable, and scalable.
6.5 Packages
We have so far used only base R: the functions that ship with R itself. Most of R’s reach comes from packages. A package is a collection of functions, datasets, and documentation, packaged together by the people who developed it. Packages let people who are not part of the R core team contribute new functions to the ecosystem and let any user benefit from those contributions.
Some packages come from the R core team and are maintained alongside R itself. The vast majority come from researchers, practitioners, and hobbyists who needed a particular tool, wrote it, documented it, and made it available. The total number of packages on the central R archive (CRAN) is in the tens of thousands and grows continuously.
A useful default attitude: when you have a task and you are about to write the code yourself, search first to see whether someone has already written a package for it. They usually have.
6.5.1 Installing and loading
Two distinct steps are involved in using a package: installing it (downloading it from the internet onto your computer) and loading it (telling the current R session to make its functions available).
You install a package once per computer. The standard command:
install.packages("psych")This downloads and installs the package called psych. The quotation marks are required. After installation, the package sits on your hard drive but is not yet active in your session.
You load a package every session in which you want to use it:
library(psych)After this line, all the functions in psych are available in the current session, just as if they were part of base R. If you restart R (which, recall from Chapter 4, you should do regularly), you will need to call library(psych) again before the package’s functions are available.
A common confusion: install.packages() requires quotes around the package name; library() does not. This is an inconsistency in R’s history; you simply have to remember it.
6.5.2 Finding documentation
After loading a package, you can read its documentation in three ways.
Help on a single function. Use ? followed by the function name:
?describeThis opens the help page for describe() in the Help panel of RStudio.
Help on the package as a whole. Each well-maintained package has an overview page:
help(package = "psych")This lists every function in the package, with a one-line description.
Vignettes. Many packages include longer narrative tutorials, called vignettes, written by the authors. To list the vignettes in a package:
vignette(package = "psych")To open one:
vignette("intro", package = "psych")Vignettes are often the best resource when learning a new package, because they show how the functions are intended to be used together.
6.5.3 A worked example: psych::describe() and describeBy()
Let us work through a concrete example using psych, a package widely used in psychology and the social sciences.
install.packages("psych") # only if you have not installed it already
library(psych)The function describe() produces a more thorough version of summary(). On a numeric vector or a data frame, it returns the number of valid cases, the mean, the standard deviation, the median, the minimum, the maximum, the range, the skewness, the kurtosis, and the standard error of the mean.
describe(survey$age)
# returns a one-row table with the columns above
describe(survey)
# returns one row per numeric columnFor a researcher working with social and behavioral data, the additional columns (skewness, kurtosis, standard error) are often exactly what you want.
describeBy() does the same, but separately for each level of a grouping variable. Suppose you also have a condition variable:
survey$condition <- c("control", "treatment", "control", "treatment", "control")
describeBy(survey$item1, group = survey$condition)
# returns a separate describe table for control and treatmentThis is a one-line operation that, in SPSS, would be a multi-step menu walk through “Split File” and then “Descriptives.”
6.5.4 An alternative without library()
There is a second way to use a package’s functions without loading it into the session: the double-colon operator ::. The syntax is package::function:
psych::describe(survey$age)This calls describe() from the psych package without having loaded psych. The package must still be installed; it just does not have to be loaded.
This style has two advantages and one cost.
The advantages: it makes the source of every function explicit (a reader can tell at a glance which package each function comes from), and it avoids problems caused by two packages defining a function with the same name (because psych::describe and Hmisc::describe, both real, are unambiguous when written with ::).
The cost: it is more verbose. Code that uses the same function many times becomes cluttered.
A reasonable convention: use library() for packages whose functions you will call frequently in a script, and use package::function style for one-off calls to functions from packages you do not otherwise need.
6.6 Summary
The chapter has covered four threads, each of which will recur throughout the rest of the book.
Basic operations are the day-to-day vocabulary of working in R. You assign a value to a name with the arrow <-. You combine values with the standard arithmetic operators (+, -, *, /, ^, plus modulo and integer division), and these operators work element-wise on vectors as naturally as they work on single numbers. You summarize a vector with mean, sd, median, min, max, sum, length, var, and the catch-all summary. You will see all of these constantly. The single non-obvious detail is that most summary functions return NA when the input contains any NA; setting na.rm = TRUE computes the summary over the non-missing values, and you will type that argument many times in real data analysis.
Custom functions were introduced for illustration. You saw the basic structure (name <- function(arguments) { body }), a small example with if and else for input checking, and the way a custom function can be called like any other. The point at this stage is to recognize the structure when you read code written by others, not to write your own. We will return to writing functions much later in the book, once using existing functions is comfortable.
The substantive example with the distorted survey was the centerpiece of the chapter. The same correction was applied to ten variables in three increasingly compact ways: ten manual assignments, ten function calls, and a single line that applies the function to all ten columns at once. The progression illustrates the three benefits coding has over click-based tools. The correction formula lives in one place, so a fix is one edit rather than ten. The code does not grow with the number of variables, so a sixty-variable dataset uses the same two working lines as a ten-variable one. And the intent is more legible than ten or sixty repeated lines. None of those benefits is available in SPSS or Excel. This is the most concrete answer the book offers to the question of why one would learn to code at all.
Packages are how the R ecosystem extends itself. A package is a collection of functions, datasets, and documentation contributed by someone (the R core team, or a researcher, or a hobbyist) and made available for anyone to install and use. The two-step install-then-load distinction matters: install.packages("name") runs once per computer, library(name) runs every R session in which you want the package’s functions to be available. You can read documentation through ?function_name, through help(package = "name") for an overview of everything in a package, or through vignette() for the longer narrative tutorials some packages include. You can also avoid loading a package entirely by writing package::function(), which is useful for one-off calls and for disambiguating functions that have the same name in different packages.
You now have the conceptual foundations of working in R. Chapter 7 is a brief recap, and after that you are ready for the rest of the book.
6.7 Check your understanding
1. What is the difference between <- and = for assignment in R?
2. What does mean() return when applied to a vector containing one or more NA values, by default?
3. Which is the correct syntax for defining a function named quick_summary that takes one argument x?
4. What is the main advantage of applying a custom function to all relevant variables at once, compared to applying it manually one variable at a time?
5. What does install.packages("psych") do?
6. How often do you need to call library(psych)?
7. What is the :: operator used for, as in psych::describe()?
8. Which of the following best describes describe() from the psych package?