5  Objects and functions

5.1 The two main verbs of R

In Chapter 1 we said that working in R consists mostly of two activities: creating objects, and feeding objects into operations to produce new objects. The operations themselves are called functions. This chapter takes that loose description and replaces it with a more precise vocabulary.

Concretely, this chapter covers:

  1. The kinds of objects R has (values, vectors, data frames, and a few related types).
  2. The fact that some objects are composed of smaller objects, and how to look inside them.
  3. What a function is and how it works in practice.
  4. How to assign objects, read what is inside them, and extract pieces of them.

5.2 Single values

The simplest kind of object in R is a single value. A number, a single piece of text, or a true/false flag are all single values.

To create a single value, you use the assignment arrow <-. The arrow points from the value to the name. The general form is name <- value.

participants <- 100
mean_age <- 21.4
study_name <- "pilot 2024"
finished <- TRUE

You have created four objects. The first two are numbers. The third is a piece of text, called a character string or just string. Strings are written between double quotes. The fourth is a logical value (TRUE or FALSE), used for true/false flags.

To inspect an object, type its name in the Console:

participants
# returns 100

R prints the value. (Throughout this book, comments starting with # indicate what R returns, so that you can read the examples without running them.)

R has different “types” for these different kinds of values: numeric for numbers, character for strings, logical for true/false. To check the type of an object:

class(participants)   # returns "numeric"
class(study_name)     # returns "character"
class(finished)       # returns "logical"

The function class() is itself an example of what we will discuss later in the chapter: a function that takes an object as input and returns information about it.

5.3 Vectors

A vector is an ordered sequence of values of the same type. In R, a vector is created with the function c() (the letter “c” stands for “combine”):

ages <- c(19, 22, 21, 25, 18, 30, 27)
genders <- c("F", "M", "F", "F", "M", "F", "M")
finished_each <- c(TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE)

ages is now a vector of seven numbers, genders is a vector of seven strings, and finished_each is a vector of seven logical values. The objects you created with single values in the previous section were technically vectors of length one; R does not formally distinguish “scalars” from “vectors of length one.” Almost everything in R is, at base, a vector.

To find the length of a vector, use length():

length(ages)
# returns 7

To extract one or more elements of a vector, use square brackets [ ]:

ages[1]        # the first element
ages[3]        # the third element
ages[c(1, 3)]  # the first and third elements together
ages[1:5]      # elements one through five

Note that R uses 1-based indexing: the first element is at position 1, not 0. (If you have used Python or some other languages, this is one of the differences to remember.)

The expression 1:5 is shorthand for the vector c(1, 2, 3, 4, 5). The colon operator generates a sequence of consecutive integers.

A common mistake is to mix types within c(). R will silently convert all elements to the most general type:

mixed <- c(1, 2, "three")
class(mixed)
# returns "character"

The first two values were converted to strings ("1" and "2") so that all elements have a common type. This is rarely what you want; if you find yourself doing this by accident, it usually means you misclassified the data on input.

In practice, at the beginner level you will rarely create vectors by hand with c(). Most of the time you will be working with vectors that came from a real data file (a CSV, a survey export, a spreadsheet). What matters at this stage is that you understand what a vector is and how to manipulate one: how to find its length, how to pull out specific elements with square brackets, and how it behaves when types are mixed. Those skills transfer directly to vectors that arrive in your environment from outside.

5.4 Data frames

A data frame is the structure most often used to represent a dataset: rows are observations (e.g., participants), columns are variables (e.g., age, gender, response on item 1). It is the R analogue of a spreadsheet.

You can create a data frame from existing vectors:

participants_data <- data.frame(
  id     = c(1, 2, 3, 4, 5, 6, 7),
  age    = c(19, 22, 21, 25, 18, 30, 27),
  gender = c("F", "M", "F", "F", "M", "F", "M"),
  finished = c(TRUE, TRUE, FALSE, TRUE, TRUE, FALSE, TRUE)
)

Now participants_data is a data frame with seven rows and four columns. To see it:

participants_data

To learn its dimensions:

nrow(participants_data)   # 7
ncol(participants_data)   # 4
dim(participants_data)    # both at once: c(7, 4)

To peek at the first few rows:

head(participants_data)        # first 6 rows by default
head(participants_data, n = 3) # first 3 rows
tail(participants_data, n = 3) # last 3 rows

To get a structural overview:

str(participants_data)

str() (for “structure”) prints a compact summary: the number of observations, the number of variables, the type of each variable, and a few sample values.

To extract one column of a data frame, use the dollar sign $:

participants_data$age
# returns the vector c(19, 22, 21, 25, 18, 30, 27)

participants_data$age returns the column age as a regular vector. You can do anything with it that you would do with any other vector:

mean(participants_data$age)
# returns 23.14286

You can also extract rows and columns by position with two-dimensional bracket indexing. The general form is dataframe[rows, columns]:

participants_data[1, ]            # first row, all columns
participants_data[, 2]            # all rows, second column
participants_data[1:3, c(1, 2)]   # first three rows, first two columns

Leaving one of the slots empty means “all”: [1, ] means “row 1, all columns,” and [, 2] means “all rows, column 2.” This pattern is worth practicing; it is used frequently.

As with vectors, at the beginner level you will rarely create data frames by hand. Most of the time you will load a data frame from a real data file (a CSV, an SPSS file, an Excel sheet) using a function like read.csv(). What matters at this stage is that you understand what a data frame is, how to inspect its structure, and how to pull out specific columns, rows, and individual cells. Those skills are exactly what you will use on real datasets.

5.5 Objects composed of objects

We have already seen this idea in passing, but it is worth making explicit. A vector is a sequence of single values. A data frame is a collection of vectors of equal length. A data frame, in turn, is itself an object that can be passed as input to functions like nrow(), mean(), str(). Larger objects are built from smaller ones.

Two more compound types are worth knowing about, even though we will not use them heavily in Section 1.

A list is an ordered collection of objects, like a vector, except that the elements can be of any type and any length. A list could contain a single number in the first slot, a vector of strings in the second slot, and a data frame in the third slot. Many functions that fit statistical models (regressions, ANOVAs) return their results as a list. We will revisit lists when we encounter such results in later sections.

A factor is a vector of strings that R has been told to treat as a fixed set of categorical levels. Factors are useful for categorical predictors in models (e.g., experimental conditions). For now, what matters is to recognize the term when you see it.

Whenever an object is composed of named parts, the dollar sign $ is the operator you use to look at, or extract, one of those parts. We saw this in the previous section, where participants_data$age returned the age column of a data frame. The same operator works on lists: if model_results is a list with a named slot called coefficients, then model_results$coefficients returns the contents of that slot. The pattern is always the same: write the name of the outer object, a dollar sign, and the name of the inner part you want.

participants_data$age          # the age column of a data frame
model_results$coefficients     # the coefficients slot of a model-results list

You will use $ constantly when working with real data and with the output of analysis functions. Most of those outputs are composed objects whose useful pieces have names; $ is the way you reach them.

5.6 Functions

A function is a piece of R that takes objects as input and produces a new object as output. We have already used several: mean(), class(), length(), nrow(), c(), data.frame(). The general form of a function call is:

function_name(input1, input2, ...)

The inputs are called arguments. The general syntax is to write the function name, an open parenthesis, the arguments separated by commas, and a close parenthesis. R passes the arguments to the function, the function does its work, and a value is returned. That returned value can be used (assigned to a name, passed to another function, printed).

A useful mental model is a machine in a factory: ingredients go in, the machine processes them, and a product comes out. R’s functions are exactly this. The “ingredients” are the objects you pass in, the “machine” is the body of the function, and the “product” is the returned object.

Here is the same function, mean, used in three different ways:

mean(ages)                          # used directly; result printed
average_age <- mean(ages)           # result assigned to a name
mean(participants_data$age)         # input pulled from a data frame using $

The third line uses the dollar sign $ introduced in the previous section: participants_data$age extracts the age column from the data frame and passes it directly to mean(), with no intermediate object. Reading this kind of expression from the inside out is a useful habit: first participants_data$age produces a vector, then mean() takes that vector and returns a single number.

Many functions accept multiple arguments. round(), for example, takes a number and an optional second argument specifying how many decimals to keep:

round(23.14286)            # 23
round(23.14286, digits = 2) # 23.14

The phrase digits = 2 is called a named argument: you are explicitly identifying which argument you are setting. You can also pass arguments by position (round(23.14286, 2)), but for any argument other than the first one or two, named arguments are clearer and less error-prone.

Every function has a help page. To open the help page for a function, type ? followed by its name in the Console:

?mean
?round
?data.frame

The help page lists the arguments, what they do, what the function returns, and usually a few examples at the bottom. Reading help pages is a skill that takes some getting used to. The examples are the most useful section for beginners; if you are unsure how to use a function, scroll directly to the bottom of its help page.

5.7 Looking inside objects

A small set of functions are constantly useful for “looking inside” objects:

class(x)        # what type of object is x?
length(x)       # how long is it?
str(x)          # a structural overview
head(x)         # the first few elements (or rows)
summary(x)      # a quick summary, type-dependent
names(x)        # the names of components, if any

For data frames specifically, you will also use:

nrow(df)        # number of rows
ncol(df)        # number of columns
colnames(df)    # column names

When you encounter an unfamiliar object (for example, the result of a function you have not used before), running class() and str() on it is a good first move. Together they tell you what kind of object you have and what is inside it.

5.8 Exercises

Below are some exercises you can do in RStudio. They are not graded; the answers will appear in your Console as you work. The aim is to get you comfortable with assigning, inspecting, and indexing objects.

Exercise 1: assignment. Create three objects:

  • n_items containing the integer 10
  • scale_name containing the string “Big Five”
  • responses containing the vector c(3, 5, 4, 2, 5, 4, 3, 4, 5, 4)

Inspect each by typing its name in the Console.

Exercise 2: type-checking. For each of the three objects above, run class(). What does each return?

Exercise 3: indexing. From responses, extract:

  • the first element
  • the last element (hint: use length(responses) inside the brackets)
  • elements 1 through 5
  • elements 6 through 10

Exercise 4: a data frame. Create a data frame with three rows and three columns:

mini_data <- data.frame(
  id     = c(1, 2, 3),
  rt_ms  = c(523, 612, 478),
  correct = c(TRUE, FALSE, TRUE)
)

Then:

  • print the data frame;
  • run str(mini_data);
  • extract the column rt_ms as a vector;
  • extract the second row;
  • extract the cell in row 1, column 2.

Exercise 5: functions. Compute the mean of responses and assign it to an object called mean_response. Then compute the mean of mini_data$rt_ms and assign it to mean_rt.

Exercise 6: help pages. Open the help page for mean (with ?mean). Find the description of the argument na.rm. What does it do? (You will encounter this argument frequently when you work with real data, where missing values are common.)

5.9 Check your understanding

1. What is a vector in R?

2. At what index is the first element of a vector in R?

3. What is a data frame?

4. Which expression extracts the column age from a data frame called participants_data?

5. What is a function?

6. What does round(23.14286, digits = 2) do?

7. If ages is a vector of length 7, what does length(ages) return?

8. What does typing ?mean in the Console do?