Final Exam Review Module 1

Unix Shell to Data Frames

Agenda

  • Unix Shell
  • Atomic Vectors
  • Matrices
  • Lists
  • Control Flow
  • Functions
  • Factors & Data Frames
  • Project 2

Unix Shell

Paths

A Path is a descripton of a file or directory’s location in the file system, written as a sequence of folder names that leads to it, separated by /

An Absolute Path is the complete, full address of a file or directory on a computer. Tip: These always start with / or ~/.

e.g. /Users/calvin/Documents/stat133, ~/Desktop/wallpapers


A Relative Path is an address of a file relative to the current shell location.

e.g. ../, stat133/projects, ../../fall-2025

Unix Shell commands and their R Equivalent

  • pwd - Print working directory.
    • getwd() in R
  • ls - Shows contents in current working directory.
    • list.files()
  • cd <path> - Change curent directory to a provided directory.
    • setwd("<path>")
  • cat <path> - Print contents of a provided file.
    • readLines("<path>")

Unix Shell commands and their R Equivalent

  • mkdir <path> - Create a directory. R equivalent not in scope.
  • cp <path1> <path2> - Copy file(s) from path1 to path2. R equivalent not in scope.
  • mv <path1> <path2> - Move file(s) from path1 to path2. R equivalent not in scope.

Terminal and R Toy Problem

~
├── stat133
│   ├── final-exam 
│   │   ├── final-exam.qmd
│   │   ├── final-exam-solutions.qmd
│   │   └── final-exam.R
│   ├── project6   
│   └── ps14
├── Desktop
└── Documents
    └── Zoom *
  • Come up with 3 ways to copy the final-exam directory to the Desktop. You are starting in *.
02:00

Vectors and Matrices

Vectors and Matrices

  • Vectors are the central data structure in R.
    • Ordered set of elements
    • Atomic: elements of the same type
    • Can name elements using names() or naming in c()
  • Matrices are vectors with dimensions dim(). All vector behavior still applies.
    • Created using matrix() function. Fills column-wise by default.

Vectorization, Recycling, Type Coersion

  • Vectorization: operations are applied element-wise to vectors
    • E.g. vec2 * 2 multiplies each element of vec2 by 2
  • Recycling: elements of a shorter vector are recycled to match the length of the longer vector
    • E.g. c(1, 2, 3, 4) - c(1, 2, 3) results in c(0, 0, 0, 3)
  • Type coercion: when combining different types, R coerces to the “highest” type
    • Logical < Integer < Double < Character
    • Implicit Coercion: c(c(1,2), TRUE) results in c(1, 2, 1)
    • Explicit Coercion: as.character(c(1, 2)) results in c("1", "2")

Subsetting

  • Vectors: use [] with numeric indices, logical vectors, or names (if named)
    • E.g. vec[c(1, 3)], vec[vec > 2], named_vec["a"]
  • Matrices: use [row_indices, col_indices] OR (less commonly) single index.
    • E.g. mat[1:2, ], mat[, c(1, 3)], mat[mat > 5]

Lists

What if I want to store different types together?

 

y <- c("a", 1L, 1.5, TRUE)
y
[1] "a"    "1"    "1.5"  "TRUE"
  • Here, R implicitly coerced all elements to the character type.

What if I want to store different types together?


y <- list("a", 1L, 1.5, TRUE)
y
[[1]]
[1] "a"

[[2]]
[1] 1

[[3]]
[1] 1.5

[[4]]
[1] TRUE
  • Preserves the types of each element.

Lists

A list is a non-atomic vector that can contain:

  1. Atomic vectors of different types
  2. Other lists

Created with list().


ys = list(list("a", 1L, 1.5, TRUE), list("b", 3L, 1.2, FALSE), 3)

List indexing:

ys = list(list("a", 1L, 1.5, TRUE), list("b", 3L, 1.2, FALSE), 3)

Single Bracket [ ]

  • Returns a train containing the selected cargo i.e. a sub-list of selected elements.
  • Use with numeric indices or names (if named)
    • e.g. ys[1], ys[c(T, F, T)]

Double Bracket [[ ]]

  • Returns the cargo directly i.e. the actual elements within the list.
  • e.g. ys[[1]], ys[[3]]

Dollar Sign $

  • Returns cargo directly. May be used with named lists.

Practice Problems

el_1 <- "crane"
el_2 <- matrix(c("a", "b", "c", "d"))
el_3 <- list(c(3.2, 5.7, 9), c(FALSE, TRUE))
lst <- list("l1" = el_1, "l2" = el_2, "l3" = el_3)

Write R code to extract the following from the list lst:

  1. The element “d”
  2. The double vector, as the sole element of a list.
  3. The value FALSE
02:00

Control Flow & Functions

Control Flow: If statements

sample_size <- 25

if (sample_size < 30) {
  print("Small sample - use t-distribution")
} else {
  print("Large sample - use normal approximation")
}
[1] "Small sample - use t-distribution"
  • Used to execute code conditionally based on logical expressions.

Control Flow: If statements

sample_size <- 25

if (sample_size < 10) {
  print("Sample too small.")
} else if (sample_size < 30) {
  print("Small sample - use t-distribution.")
} else {
  print("Large sample - use normal approximation.")
}
[1] "Small sample - use t-distribution."

Control Flow: Vectorized ifelse

  • ifelse(test, yes, no) is a vectorized version of if-else statements.
ages <- c(19, 20, 21, 24)
ifelse(ages %% 2 == 0, "even age", "odd age")
[1] "odd age"  "even age" "odd age"  "even age"

Control Flow: For Loops

  • Used to iterate over a sequence (vector, list, etc.)
  • Two common utilities:
    • Smart for loops: iterating over elements directly
    • Index-based for loops: iterating over indices

Control Flow: For Loops

grades <- c(88, 32, 95, 76)

for (grade in grades) { 
  if (grade < 70) {
    print("NP")
  } else {
    print("P")
  }
}
[1] "P"
[1] "NP"
[1] "P"
[1] "P"

Control Flow: For Loops

grades <- c(88, 32, 95, 76)
grades_str = rep(NA, 4)
for (i in 1:length(grades)) { 
  if (grades[i] < 70) {
    grades_str[i] <- "NP"
  } else {
    grades_str[i] <- "P"
  }
}
grades_str
[1] "P"  "NP" "P"  "P" 

Functions

  • Functions are reusable chunks of code that perform specific tasks.
    • DRY: Don’t Repeat Yourself
  • Defined using the function() keyword.
  • Can take in arguments and return values.

Functions

grade_PNP <- function(grades) {
  grades_str <- rep(NA, length(grades))
  for (i in 1:length(grades)) {
    if (grades[i] < 70) grades_str[i] <- "NP"
    else grades_str[i] <- "P"
  }
  return(grades_str)
}
grades_stat133 <- c(71, 99, 84, 90)
grades_stat134 <- c(88, 32, 95, 76)

grade_PNP(grades_stat133)
[1] "P" "P" "P" "P"
grade_PNP(grades_stat134)
[1] "P"  "NP" "P"  "P" 

Practice Problem

Create an R function that iterates through x and prints:

Fruit 1: apple
Fruit 2: banana
Halfway there!
Fruit 3: cherry
Fruit 4: peach


x <- c("apple", "banana", "cherry", "peach")
fruit_list <- function(x) {
  # your code here
}
02:00

Factors and Data Frames

Factors

A data structure for storing categorical data. Stores the values in an integer vector and adds a levels attribute to map integers to character strings. Created with factor().

stat133_grades <- c(
  "A", "F", "NP", "A", "P", "B-",
  "B+", "B+", "B-", "A-", "C",
  "A-", "B", "C+", "C-", "D", "A"
)
factor(stat133_grades)
 [1] A  F  NP A  P  B- B+ B+ B- A- C  A- B  C+ C- D  A 
Levels: A A- B B- B+ C C- C+ D F NP P

Factor Utility

as.integer(stat133_grades)
Warning: NAs introduced by coercion
 [1] NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA NA
summary(stat133_grades)
   Length     Class      Mode 
       17 character character 
s133_grades_factor <- factor(stat133_grades)
as.integer(s133_grades_factor)
 [1]  1 10 11  1 12  4  5  5  4  2  6  2  3  8  7  9  1
summary(s133_grades_factor)
 A A-  B B- B+  C C- C+  D  F NP  P 
 3  2  1  2  2  1  1  1  1  1  1  1 
  • Can be used to convert character vectors to integer codes representing categories.

Factor Utility

s133_grades_f_ordered <- factor(stat133_grades,
                                levels = c("A", "A-", "B+", "B",
                                           "B-", "C+", "C", "C-",
                                           "D+", "D", "D-", "P",
                                           "NP", "F"),
                                ordered = TRUE)
s133_grades_f_ordered
 [1] A  F  NP A  P  B- B+ B+ B- A- C  A- B  C+ C- D  A 
Levels: A < A- < B+ < B < B- < C+ < C < C- < D+ < D < D- < P < NP < F
  • Can provide order to categorical data by specifying levels and setting ordered=TRUE.

Factor Utility

barplot with unordered factor

barplot(summary(s133_grades_factor))

barplot with ordered factor

barplot(summary(s133_grades_f_ordered))

Data Frames

A data frame is a named list of vectors of the same length. Holds attributes for (column) names, row.names, and its class, “data.frame”. Created with data.frame().

  • Address the limitations of matrices, allowing for different data types in each column.

  • Allow for easier data manipulation using packages like dplyr and tidyr.

Data Frames: Example

star_wars <- data.frame(
    name = c("Anakin", "Padme", "Luke", "Leia"),
    gender = c("male", "female", "male", "female"),
    height = c(1.88, 1.65, 1.72, 1.50),
    weight = c(84, 45, 77, 49)
)
star_wars
    name gender height weight
1 Anakin   male   1.88     84
2  Padme female   1.65     45
3   Luke   male   1.72     77
4   Leia female   1.50     49

Tibbles

A modern reimagining of data frames provided by the tibble package. Tibbles are part of the tidyverse and offer enhanced printing, subsetting, and type consistency.

star_wars_tbl <- tibble::as_tibble(star_wars)
star_wars_tbl
# A tibble: 4 × 4
  name   gender height weight
  <chr>  <chr>   <dbl>  <dbl>
1 Anakin male     1.88     84
2 Padme  female   1.65     45
3 Luke   male     1.72     77
4 Leia   female   1.5      49