JSTAcademy
0 XP
Dashboard
Crash Courses
Vectors, Matrices & Data Frames
14 min
Basic+160 XP
Crash Courses · Basic

Vectors, Matrices & Data Frames

Master R's core data structures — from atomic vectors to the data frame, the workhorse of data analysis.
14 min read+160 XP on completionCert: R Crash Course
Tap any word in the text below to start reading from there.

Vectors, Matrices & Data Frames

Vectors

# Creating vectors
x <- c(1, 2, 3, 4, 5)         # numeric
chars <- c("a", "b", "c")      # character
logic <- c(TRUE, FALSE, TRUE)  # logical
ints  <- 1:10                  # integer sequence

# Named vectors
scores <- c(Alice=95, Bob=88, Carol=72, David=91)
scores["Alice"]   # 95
scores[c("Bob", "Carol")]  # 88 72

# Vectorized operations
x * 2         # c(2, 4, 6, 8, 10)
x + c(10, 20) # c(11, 22, 13, 24, 15) — recycling
x > 3         # c(FALSE, FALSE, FALSE, TRUE, TRUE)

# Subsetting
x[2]           # 2  (1-indexed!)
x[2:4]         # c(2, 3, 4)
x[c(1, 3, 5)]  # c(1, 3, 5)
x[x > 3]       # c(4, 5) — logical subsetting
x[-1]          # c(2, 3, 4, 5) — exclude first

---

Useful Vector Functions

v <- c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3)

length(v)       # 10
sum(v)          # 39
cumsum(v)       # running cumulative sum
diff(v)         # differences between consecutive elements
rev(v)          # reversed
sort(v)         # sorted ascending
order(v)        # indices that would sort v
unique(v)       # c(3, 1, 4, 5, 9, 2, 6) — deduplicated
table(v)        # frequency count of each value
which(v > 4)    # indices where condition is TRUE
any(v > 8)      # TRUE — any element > 8?
all(v > 0)      # TRUE — all elements > 0?

---

Matrices

# Create from vector
m <- matrix(1:12, nrow=3, ncol=4)
#      [,1] [,2] [,3] [,4]
# [1,]    1    4    7   10
# [2,]    2    5    8   11
# [3,]    3    6    9   12
# Filled column-by-column (col-major order)

# Dimensions
dim(m)    # c(3, 4)
nrow(m)   # 3
ncol(m)   # 4

# Subsetting [row, col]
m[1, ]    # first row: c(1, 4, 7, 10)
m[, 2]    # second column: c(4, 5, 6)
m[2, 3]   # element at row 2, col 3: 8

# Matrix arithmetic (element-wise)
m * 2     # doubles every element
m %*% t(m)  # matrix multiplication (with transpose)
apply(m, 1, sum)  # row sums: c(22, 26, 30)
apply(m, 2, sum)  # column sums: c(6, 15, 24, 33)

---

Lists

# Lists hold heterogeneous elements
person <- list(
    name  = "Jordan",
    age   = 28,
    scores = c(95, 88, 92),
    active = TRUE
)

# Access with $ or [[]]
person$name         # "Jordan"
person[["age"]]     # 28
person$scores[2]    # 88

str(person)  # shows structure of any object
# List of 4
#  $ name  : chr "Jordan"
#  $ age   : num 28
#  $ scores: num [1:3] 95 88 92
#  $ active: logi TRUE

---

Data Frames — The Core of R Analysis

# Create a data frame
students <- data.frame(
    name    = c("Alice", "Bob", "Carol", "David", "Emma"),
    age     = c(22, 25, 21, 23, 24),
    score   = c(92.5, 78.0, 95.5, 61.0, 88.5),
    passed  = c(TRUE, TRUE, TRUE, FALSE, TRUE),
    grade   = factor(c("A", "C", "A", "F", "B")),
    stringsAsFactors = FALSE
)

# Dimensions and structure
dim(students)   # c(5, 5)
str(students)   # shows types and preview
head(students)  # first 6 rows (or n rows with head(df, n))
tail(students)  # last 6 rows
summary(students)  # statistical summary per column

# Column access
students$name    # character vector of names
students[["score"]]  # same as $score

# Row and column subsetting [rows, cols]
students[1, ]           # first row (all cols)
students[, "score"]     # score column
students[1:3, c("name", "score")]  # rows 1–3, two columns

# Conditional subsetting
students[students$score >= 85, ]
students[students$grade == "A", "name"]

# Adding a column
students$letter_grade <- ifelse(students$score >= 90, "A",
                         ifelse(students$score >= 80, "B",
                         ifelse(students$score >= 70, "C", "F")))

# nrow, ncol
nrow(students)  # 5
ncol(students)  # 6 (after adding letter_grade)

---

Factors

sizes <- factor(c("S", "L", "M", "S", "XL", "M"),
                levels = c("S", "M", "L", "XL"))  # ordered levels

levels(sizes)  # "S" "M" "L" "XL"
table(sizes)   # frequency count by level
as.integer(sizes)  # numeric codes: 1 2 2 1 4 2

# Ordered factor for statistics
rating <- factor(c("low", "high", "medium", "low"),
                 levels = c("low", "medium", "high"),
                 ordered = TRUE)
rating[1] < rating[2]  # TRUE — "low" < "high"
0%