Lesson 5 / 25

Lists, Factors and Matrices

Use lists for mixed data, factors for categories and matrices for 2D numeric data.

Beyond simple vectors

A list holds elements of different types and lengths, including other lists, making it R's general-purpose container: results of a model, a parsed JSON document, or a record about a customer. Access elements with [[ ]] or $ (order$items), while single brackets [ ] return a sub-list. A factor represents categorical data with a fixed set of levels, stored as integers with labels; factors control the order of categories in plots and models, and ordered factors support comparisons such as "low" < "high". The forcats package helps reorder, lump and relabel levels. A matrix is a two-dimensional atomic vector (all one type) with rows and columns, indexed as m[row, col], and supports matrix algebra (%*% for multiplication, t() for transpose, solve() for inverses); arrays generalise to more dimensions. Use str() to inspect the structure of any object quickly.

Lists, factors and a matrix

[[ ]] extracts an element; [ ] returns a smaller list.

order <- list(
  id = "o-1001",
  customer = "Asha",
  items = c("pen", "notebook"),
  totals = list(subtotal = 169.5, gst = 30.51)
)

order$items                    # character vector
order[["totals"]]$gst          # nested access
order["id"]                    # a list containing id
str(order)                     # compact structure overview

sizes <- factor(c("M", "S", "L", "M"), levels = c("S", "M", "L"), ordered = TRUE)
levels(sizes)                  # "S" "M" "L"
table(sizes)                   # counts in level order
sizes[1] < sizes[3]            # TRUE: M < L

sales <- matrix(c(10, 12, 8, 15, 9, 11), nrow = 2, byrow = TRUE,
                dimnames = list(c("Pune", "Delhi"), c("Jan", "Feb", "Mar")))
sales["Delhi", "Feb"]          # 9
rowSums(sales)                 # Pune 30, Delhi 35

A folder versus the paper inside

A list is a folder. order["items"] hands you a smaller folder containing the items page; order[["items"]] takes the page itself out of the folder.

Quick check: For a list x, what is the difference between x["a"] and x[["a"]]?

  • There is none
  • x["a"] returns a sub-list; x[["a"]] returns the element itself
  • x[["a"]] returns a sub-list
  • Both throw errors
Answer

x["a"] returns a sub-list; x[["a"]] returns the element itself — Single brackets keep the list container; double brackets extract the content.