Basic Data Operations and Control Flow

Article · 2:00

The three subsetting operators and when each one is right, conditionals, loops, and the built-in functions that make most loops unnecessary.

Subsetting is where R is least like other languages and most worth slowing down for. There are three operators and they do different things.

[ ] keeps the container. df[1:3, ] is a data frame of three rows; list[1] is a list of one element. [[ ]] extracts the contents: list[[1]] is the thing itself. $ is [[ ]] by name with less typing, and works only for a literal name you type out - you cannot use a variable with it, which is the usual reason to reach for [[ ]] instead.

The mnemonic that sticks: if a list is a train of carriages, [ ] gives you a shorter train and [[ ]] gives you what is inside one carriage.

R's indexing has three forms other languages do not combine. Positive indices select, negative indices drop (x[-1] is everything except the first - not "the last", which is the Python reading and a real source of confusion), and logical indices select wherever TRUE. That last form is how nearly all filtering is done: df[df$born > 1900, ] reads as "the rows where born exceeds 1900".

And R indexes from 1, not 0. There is no x[0] - it returns an empty vector rather than an error, which is worse.

Conditionals. if/else works on a single value, and in R 4.2 and later it is an error to pass it a vector of length greater than one. ifelse() is the vectorized version, taking a whole logical vector and returning an element per input - that is the one to use on a data frame column. switch() handles several named cases.

Loops exist - for, while, repeat - and are not as slow as R folklore claims, provided you pre-allocate. The real cost is growing an object inside a loop: result <- c(result, x) copies the whole vector every iteration, making a linear loop quadratic. Pre-allocate with vector("numeric", n) and assign by index.

But most loops in R should not be loops at all. The language is vectorized: sum(x), mean(x) and x * 2 all operate on the whole vector in compiled C. A loop that does arithmetic element by element is both slower and longer than the vectorized line that replaces it. The apply family generalises this, and phase 2 replaces it with purrr.

df <- data.frame(
  name = c("ada", "grace", "alan", "edsger"),
  born = c(1815, 1906, 1912, 1930),
  field = c("maths", "navy", "logic", "logic")
)

# ---- [ ] keeps the container, [[ ]] extracts the contents ------------
l <- list(a = 1, b = "two", c = c(3, 4))

l[1]        # a LIST of length one
l[[1]]      # the number 1
l$a         # the number 1, same as [[ ]], but only for a literal name

key <- "a"
# l$key     # NULL - $ does not evaluate a variable
l[[key]]    # 1     - [[ ]] does. This is why [[ ]] exists.

# ---- Data frame subsetting: [rows, columns] --------------------------
df[1, ]            # row 1, all columns          -> a data frame
df[, "name"]       # the name column             -> a VECTOR
df["name"]         # the name column             -> a DATA FRAME
df[[2]]            # the second column           -> a vector
df$born            # the born column             -> a vector

df[df$born > 1900, ]              # logical index: the usual way to filter
df[df$born > 1900, c("name")]     # and pick columns while you are there
subset(df, born > 1900, select = name)   # the base R convenience version

# ---- Negative indices DROP. They do not count from the end. ----------
x <- c(10, 20, 30, 40, 50)
x[1]        # 10
x[-1]       # 20 30 40 50      <- NOT "the last element"
x[c(-1, -2)]# 30 40 50
x[length(x)]# 50               <- this is how you get the last one
x[0]        # numeric(0)       <- empty, not an error. R counts from 1.

# ---- Conditionals ----------------------------------------------------
score <- 72
if (score >= 90) {
  "A"
} else if (score >= 70) {
  "B"
} else {
  "C"
}

# if() takes ONE value. In R >= 4.2 a longer vector is an error.
# For a column, use the vectorized form:
df$era <- ifelse(df$born < 1900, "19th century", "20th century")

# Several cases, by name:
role <- "admiral"
switch(role, admiral = "navy", professor = "university", "unknown")

# ---- Loops: pre-allocate, or pay for it ------------------------------
n <- 1000

# The slow way. result is copied in full, every iteration.
result <- c()
for (i in 1:n) { result <- c(result, i^2) }

# Pre-allocated: one object, written in place.
result <- vector("numeric", n)
for (i in seq_len(n)) { result[i] <- i^2 }
#       ^^^^^^^^^^^ seq_len(n), not 1:n. When n is 0, 1:n gives c(1, 0)
#       and the loop runs twice backwards. seq_len(0) gives nothing.

# The vectorized line that replaces the whole loop:
result <- (1:n)^2

# ---- Built-in functions ----------------------------------------------
x <- c(4, 8, 15, 16, 23, 42, NA)

sum(x)                  # NA  - missing data propagates, by design
sum(x, na.rm = TRUE)    # 108 - you have to say you meant to ignore it
mean(x, na.rm = TRUE)
median(x, na.rm = TRUE); sd(x, na.rm = TRUE); var(x, na.rm = TRUE)
range(x, na.rm = TRUE); quantile(x, na.rm = TRUE)

round(3.14159, 2); sqrt(16); abs(-5); exp(1); log(100, base = 10)

# Strings, in base R. stringr in phase 2 is more consistent.
s <- "Grace Hopper"
nchar(s)                      # 12
toupper(s); tolower(s)
substr(s, 1, 5)               # "Grace"
strsplit(s, " ")              # a LIST containing c("Grace", "Hopper")
paste("a", "b", sep = "-")    # "a-b"
paste0("a", "b")              # "ab"
gsub("o", "0", s)             # "Grace H0pper"  - all matches
sub("o", "0", s)              # "Grace H0pper"  - the first only
trimws("  padded  ")

# The apply family: a loop, written as one line
sapply(df[, c("born")], class)
tapply(df$born, df$field, mean)    # mean born, by field

Discussion

No questions on this topic yet. Sign in to ask the first one.