[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
STAT 204 โ Introduction to Statistical Data Analysis
01 Oct 2026
Programming is a systematic way to think about a problem โ turning a fuzzy question into precise definitions and a chain of answers. Learning R is how we build that mental model.
Thereโs no point using AI if youโre trying to build that mental model yourself.
On Tuesday we covered:
ls(), rm(), exists() ๐งนc(), seq(), rep(), special values (NA, NaN, Inf), recycling, subsetting, which(), set operations ๐The Week 1 deck has everything else we planned โ today we pick it up from matrices.
Thursday โ Data structures
Tuesday โ Programming & data import
apply()Matrices are 2-dimensional arrays that store data of the same type:
[,1] [,2] [,3] [,4]
[1,] 1 4 7 10
[2,] 2 5 8 11
[3,] 3 6 9 12
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] 5 6 7 8
[3,] 9 10 11 12
[1] 3 4
Col1 Col2 Col3 Col4
Row1 1 4 7 10
Row2 2 5 8 11
Row3 3 6 9 12
[1] 4
Col1 Col2 Col3 Col4
2 5 8 11
Row1 Row2 Row3
7 8 9
Col2 Col3 Col4
Row1 4 7 10
Row2 5 8 11
[1] 4
[1] 5
Linear algebra (%*%, solve(), t()), sweep(), and arrays are in the Self-Guided Practice section at the end.
A list can contain elements of different types:
[] vs [[]][] returns a list; [[]] returns the element:
[[]]$ and [["name"]]# A tibble: 344 ร 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
<fct> <fct> <dbl> <dbl> <int> <int>
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18 195 3250
4 Adelie Torgersen NA NA NA NA
5 Adelie Torgersen 36.7 19.3 193 3450
6 Adelie Torgersen 39.3 20.6 190 3650
7 Adelie Torgersen 38.9 17.8 181 3625
8 Adelie Torgersen 39.2 19.6 195 4675
9 Adelie Torgersen 34.1 18.1 193 3475
10 Adelie Torgersen 42 20.2 190 4250
# โน 334 more rows
# โน 2 more variables: sex <fct>, year <int>
# A tibble: 6 ร 8
species island bill_length_mm bill_depth_mm flipper_length_mm body_mass_g
<fct> <fct> <dbl> <dbl> <int> <int>
1 Adelie Torgersen 39.1 18.7 181 3750
2 Adelie Torgersen 39.5 17.4 186 3800
3 Adelie Torgersen 40.3 18 195 3250
4 Adelie Torgersen NA NA NA NA
5 Adelie Torgersen 36.7 19.3 193 3450
6 Adelie Torgersen 39.3 20.6 190 3650
# โน 2 more variables: sex <fct>, year <int>
species island bill_length_mm bill_depth_mm
Adelie :152 Biscoe :168 Min. :32.10 Min. :13.10
Chinstrap: 68 Dream :124 1st Qu.:39.23 1st Qu.:15.60
Gentoo :124 Torgersen: 52 Median :44.45 Median :17.30
Mean :43.92 Mean :17.15
3rd Qu.:48.50 3rd Qu.:18.70
Max. :59.60 Max. :21.50
NAs :2 NAs :2
flipper_length_mm body_mass_g sex year
Min. :172.0 Min. :2700 female:165 Min. :2007
1st Qu.:190.0 1st Qu.:3550 male :168 1st Qu.:2007
Median :197.0 Median :4050 NAs : 11 Median :2008
Mean :200.9 Mean :4202 Mean :2008
3rd Qu.:213.0 3rd Qu.:4750 3rd Qu.:2009
Max. :231.0 Max. :6300 Max. :2009
NAs :2 NAs :2
tibble [344 ร 8] (S3: tbl_df/tbl/data.frame)
$ species : Factor w/ 3 levels "Adelie","Chinstrap",..: 1 1 1 1 1 1 1 1 1 1 ...
$ island : Factor w/ 3 levels "Biscoe","Dream",..: 3 3 3 3 3 3 3 3 3 3 ...
$ bill_length_mm : num [1:344] 39.1 39.5 40.3 NA 36.7 39.3 38.9 39.2 34.1 42 ...
$ bill_depth_mm : num [1:344] 18.7 17.4 18 NA 19.3 20.6 17.8 19.6 18.1 20.2 ...
$ flipper_length_mm: int [1:344] 181 186 195 NA 193 190 181 195 193 190 ...
$ body_mass_g : int [1:344] 3750 3800 3250 NA 3450 3650 3625 4675 3475 4250 ...
$ sex : Factor w/ 2 levels "female","male": 2 1 1 NA 1 2 1 2 NA NA ...
$ year : int [1:344] 2007 2007 2007 2007 2007 2007 2007 2007 2007 2007 ...
Explore the penguins! (8 minutes) ๐ง
Working with a partner:
View(penguins) to open the data in a spreadsheet-like viewmean(penguins$bill_length_mm, na.rm = TRUE))table(penguins$island))Discuss: What interesting patterns do you notice? ๐
Every standard distribution has four functions: d (density), p (CDF), q (quantile), r (random draws):
Random draws change every time โ set.seed() makes them reproducible:
Part A: Data Frames
Part B: Random Numbers
Packages are collections of functions that extend R:
Popular packages ๐ฆ
?mean # Help for a function (same as help(mean))
??regression # Search all help pages (same as help.search())
example(mean) # Run the examples from the help page
help(package = "palmerpenguins") # Help for a whole package
apropos("mean") # Functions whose name contains "mean"
find("mean") # Which package a function lives inOther ways to get help ๐
Your mission (15 minutes) ๐ฏ
Create a simple analysis of your class!
student_names, birth_months, favorite_numbers. Assign 50 random numbers to months (from 1 to 12), 50 random numbers from 0 to 100 in the favorite numbers column, and use the package randomNames to generate 50 names. Create a data frame with all three columns.Bonus: Try to find out which birth month is most common using table() ๐๏ธ
Work in pairs and help each other! ๐ฅ
[1] 5
[1] 10
Error in `Mean()`:
! could not find function "Mean"
Error:
! object 'Penguins' not found
Use <- for assignment ๐
Itโs the R convention, it canโt be confused with ==, and it shows the direction of assignment. Inside a function call, = names an argument: mean(x = c(1, 2, 3)).
Keyboard shortcut: Alt + - (Windows) or Option + - (Mac)
maen() instead of mean() โ use tab-completion โ
mean instead of mean() โ functions need () โ
name <- Alice instead of name <- "Alice" โ text needs quotes โ
Reading error messages ๐
Donโt panic ๐ โ read the message ๐ โ check for typos โ๏ธ โ search the error if youโre stuck ๐
Tuesday: functions, loops, conditionals, and getting data into R.
Default values make functions flexible!
To see calculations, use print():
Only printed output is shown!
How R evaluates function arguments is not covered live โ see the Self-Guided Practice section at the end of these slides, or bring questions to the Wednesday self-guided session.
Write these functions:
my_range() - takes a vector and returns max - minstandardize() - takes a vector and returns (x - mean)/sdmy_summary() - takes a vector and returns a named list with mean, median, and sdTest your functions on:
Bonus: Modify my_summary() to handle NA values
How R resolves free variables in functions is not covered live โ see the Self-Guided Practice section at the end of these slides, or bring questions to the Wednesday self-guided session.
Store frequently-used functions in a file:
Make sure the file is in your working directory or provide full path!
Pre-allocate memory!
Memory allocation is expensive!
Vectorized functions are much faster!
apply Functionapply(X, MARGIN, FUN) runs a function over rows (1) or columns (2) of a matrix:
Math Science History English
Student1 85 96 91 94
Student2 92 88 89 82
Student3 78 74 76 90
Student1 Student2 Student3
91.50 87.75 79.50
Math Science History English
78 74 76 82
Extra arguments are passed on to the function:
We looked at two different ways to standardize the columns of a matrix:
Your task: Find a third approach and compare the computation time to the first two approaches. Post your solution on Ed Discussion.
Hint: Consider using sweep() (see Sweeping in the Self-Guided Practice section) or vectorization with matrix operations
expand.grid FunctionEvaluate functions on a 2D grid:
Finding the Minimum of a Function
Consider the following function:
\(f(x, y) = (1.5 - x + xy)^2 + (2.25 - x + xy^2)^2 + (2.625 - x + xy^3)^2\)
where possible inputs for \(x\) and \(y\) are from -4 to 4 in increments of 0.1.
Your tasks:
expand.grid()Hint: Use which.min() to find the index of the minimum value
Save specific objects (reload them later with load()):
For small datasets:
Text file with headers:
Tips for preparing data:
Same number of columns per row
Use NA for missing data
Remove special characters
Replace spaces in headers with underscores
authors <- data.frame(
surname = c("Tukey", "Venables", "Tierney", "Ripley", "McNeil"),
nationality = c("US", "AUS", "US", "UK", "AUS")
)
books <- data.frame(
name = c("Tukey", "Venables", "Tierney", "Ripley", "Ripley", "McNeil", "R Core"),
title = c("Exploratory Data Analysis", "Modern Applied Statistics",
"LISP-STAT", "Spatial Statistics", "Stochastic Simulation",
"Interactive Data Analysis", "An Introduction to R")
)
m1 <- merge(authors, books, by.x = "surname", by.y = "name")Only matching rows are kept by default!
Think-pair-share (5 minutes) โฑ๏ธ
Think (1 min): Name one thing you learned about R this week that you didnโt know before.
Pair (2 min): Share with your neighbor and listen to their surprise ๐ฅ
Share (2 min): Share it on Ed Discussion ๐ฃ๏ธ
Remember: Every expert was once a beginner! ๐ฑ
Resources:
?function_name??keywordNext week: Numerical summaries, categorical data, and exploratory data analysis ๐
The following slides were part of this weekโs original material but are not covered live. Work through them on your own, or bring questions to the Wednesday self-guided session.
R doesnโt check unused arguments:
R allows free variables in functions:
Warning: Avoid free variables unless you know what youโre doing! Can cause unexpected behavior.
[,1] [,2]
[1,] 2 3
[2,] 1 4
[,1] [,2]
[1,] 1 2
[2,] 2 1
[,1] [,2]
[1,] 3 5
[2,] 3 5
[,1] [,2]
[1,] 1 1
[2,] -1 3
[,1] [,2]
[1,] 2 6
[2,] 2 4
[,1] [,2]
[1,] 8 7
[2,] 9 6
[,1] [,2]
[1,] 2 1
[2,] 3 4
[1] 5
[,1] [,2]
[1,] 0.8 -0.6
[2,] -0.2 0.4
eigen() decomposition
$values
[1] 5 1
$vectors
[,1] [,2]
[1,] -0.7071068 -0.9486833
[2,] -0.7071068 0.3162278
[,1] [,2]
[1,] 1 -1.110223e-16
[2,] 0 1.000000e+00
The sweep() function sweeps out a statistic from a matrix:
Subtract column means:
Each column now has mean = 0!
R supports higher-order arrays:
## , , 1
## [,1] [,2]
## [1,] 1 5
## [2,] 2 6
## [3,] 3 7
## [4,] 4 8
##
## , , 2
## [,1] [,2]
## [1,] 9 13
## [2,] 10 14
## [3,] 11 15
## [4,] 12 16
Quarto has built-in support for LaTeX typesetting:
Quarto combines code, text, and output in one document:
# My Analysis
::: {.cell}
```{.r .cell-code}
# This code will run and show results
summary(penguins)
```
::: {.cell-output .cell-output-stdout}
```
species island bill_length_mm bill_depth_mm
Adelie :152 Biscoe :168 Min. :32.10 Min. :13.10
Chinstrap: 68 Dream :124 1st Qu.:39.23 1st Qu.:15.60
Gentoo :124 Torgersen: 52 Median :44.45 Median :17.30
Mean :43.92 Mean :17.15
3rd Qu.:48.50 3rd Qu.:18.70
Max. :59.60 Max. :21.50
NAs :2 NAs :2
flipper_length_mm body_mass_g sex year
Min. :172.0 Min. :2700 female:165 Min. :2007
1st Qu.:190.0 1st Qu.:3550 male :168 1st Qu.:2007
Median :197.0 Median :4050 NAs : 11 Median :2008
Mean :200.9 Mean :4202 Mean :2008
3rd Qu.:213.0 3rd Qu.:4750 3rd Qu.:2009
Max. :231.0 Max. :6300 Max. :2009
NAs :2 NAs :2
```
:::
:::
The mean bill length is 43.9219298 mm.![]()
STAT 204 โ Intro to Statistical Data Analysis