What R Is and Installing It
Getting Started
R in one paragraph
R is a free, open-source statistical software and programming language. You type commands at a console (or run them from a script), R prints the result, and anything you name with <- is kept in memory for later. Everything on this sheet — data structures, tests, models, graphs — is a command you can copy, paste and run.
- Go to https://cran.r-project.org
- Click Download R for your operating system (Linux, OS X or Windows)
- Choose the base distribution and click Download R x.x.x for …
- Run the installer with the defaults
CRAN (the Comprehensive R Archive Network) hosts R itself, every package, and the official manuals.
- Go to https://rstudio.com and download the free desktop version
- Install it after R; it finds your R installation automatically
- Open RStudio, not R, from now on
RStudio is an IDE (integrated development environment): a script editor, the console, your environment of saved objects and a plot/help pane in one window. The import tool on the Data In and Out tab lives here.
How this sheet shows code
Dark blocks are what you type. The lighter block under each one is what R prints back. In the console R prefixes its messages with ## in these notes, so you can tell output from input — the ## is not something you type.
x <- c(3, 2, 5, 6, 55)
x## [1] 3 2 5 6 55- Assign with
<-.x <- 5stores 5 under the name x.=also works but<-is the convention. - Case matters.
Mean()is notmean();TRUEandTare true,trueis an error. - Comment with
#. R ignores everything after it on that line. Comments in this sheet explain the arguments of each command.
- [1] — the index of the first value on that output line;
[7]means the line starts at the seventh element - NA — a missing value
- $ — reach into a named part of an object:
cars$mpg - ~ — “is modeled by” in a formula:
mpg ~ origin - … — the function accepts further arguments
Packages
Getting Started
Install once, load every session
Base R comes with numerous basic functions, like mean() and median(), and procedures such as lm() for linear regression. More advanced tools live in packages. Here we install ggplot2, a package for advanced graphics.
install.packages("ggplot2")Information scrolls past in the console as it installs. No errors means the package is installed. Quotes around the name are required here.
library(ggplot2)## Warning: package 'ggplot2' was built under R version 3.1.3You will often see this warning; there is rarely a compatibility issue. No quotes are needed in library().
Install once, load each time. install.packages() puts the package on your computer. library() makes it available in the current session, and must be run again every time you restart R. Forgetting the second step is the single most common “function not found” error.
Error in library(pwr) : there is no package called ‘pwr’— step 1 was never done on this computer (or was done under a different R version). Runinstall.packages("pwr"), thenlibrary(pwr)again.Error in pwr.t.test(n = 30, d = 0.4) : could not find function "pwr.t.test"— the package is installed but not loaded in this session. Runlibrary(pwr). The same message for a base function (could not find function "Mean") means a typo: R is case-sensitive.- A prompt asking to use a personal library, or about restarting R — answer Yes; both are normal on a first install.
Packages used on this sheet
| Package | Used for | Install |
|---|---|---|
ggplot2 | advanced graphics (the example above) | install.packages("ggplot2") |
pwr | power analysis and sample-size planning | install.packages("pwr") |
lme4 | linear mixed models with lmer() | install.packages("lme4") |
car | Anova() significance tests for mixed models | install.packages("car") |
Everything else on this sheet — t.test(), chisq.test(), aov(), lm(), glm(), plot() — is in base R and needs no installation.
Getting Help
Getting Started
Built-in documentation
R provides extensive documentation. Every function has a help page listing its arguments, their defaults, and examples at the bottom you can paste into the console.
?mean
help(mean)
help(c)Both forms open the same page. help(c) documents the c() function that builds vectors. Try it — the page opens in RStudio’s Help pane.
apropos("nova")## [1] "anova" "manova" "power.anova.test" "stat.anova"
## [5] "summary.manova"apropos() lists every loaded function whose name contains the text. Here it finds all the ANOVA-related functions.
Three more that pay for themselves: ??regression (two question marks) searches the help pages of every installed package for a word, not just the loaded ones; args(t.test) prints just the argument list with its defaults, which is the part of the help page you usually want; and example(t.test) runs the examples at the bottom of the page so you can see real output before trying your own data.
Beyond the console
- R-intro.pdf — An Introduction to R
- R-admin.pdf — R Installation and Administration
- R-data.pdf — R Data Import/Export
- R-exts.pdf — Writing R Extensions
- R-lang.pdf — R Language Definition
The files may be in different formats (pdf, html, texi, …) depending on your installation.
- cran.r-project.org — documents, bibliographic resources, a list of books and articles about R, and tutorials written by R users
- rseek.org — an R-specific internet search engine; searching “R” on a general engine returns noise, this does not
- the Examples section — at the bottom of every help page; run them with
example(mean)
This sheet follows the Purdue Statistical Consulting Service’s R Tutorial (2016, updated 2020).
Vectors
Data Structures
The basic building block
A vector is a contiguous collection of objects of the same type. Common types are logical, integer, double (decimal) and character. Build one with c(), where c stands for concatenate; separate the values with commas.
x <- c(3,2,5,6,55)
x## [1] 3 2 5 6 55y <- c("a", "d", "e", "hi")
y## [1] "a" "d" "e" "hi"x is a vector of numbers and y a vector of characters. You can put as many items as you want inside a vector.
Typing the name of a vector as a command prints its elements in order. The [1] at the start of the output is the position of the first element on that line, not part of the data.
One element
x[3]## [1] 5Square brackets ask for the third element of x. R counts from 1, not 0.
A vector of length one
cool <- 4
cool## [1] 4A single number is still a vector — one with length one. There is no separate “scalar” type.
Ways to build a vector
| Command | Result | What it does |
|---|---|---|
c(2,3,7,5,8) | 2 3 7 5 8 | concatenate the listed values |
rep(4, 5) | 4 4 4 4 4 | repeat: the first number, the second number of times |
33:37 | 33 34 35 36 37 | the colon counts by one from start to end |
seq(23, 31, 2) | 23 25 27 29 31 | sequence: start, end, and the step to increase by |
length(x) | 5 | how many elements x holds |
These same four commands fill the rows of the matrix on the next tab.
x + 1—4 3 6 7 56: arithmetic applies to every element at once (R is vectorized), so there is almost never a loop over a vector.x[6]—NA, with no error: asking past the end of a vector silently returns a missing value. An unexpected NA in a result often started here.c(1, "a")—"1" "a": a vector holds one type, so the number is converted to a character string. One stray text value in a column of numbers turns the whole column into text, andmean()then fails.1:3 + 1:2—2 4 4plusWarning message: longer object length is not a multiple of shorter object length: the shorter vector is recycled. Lengths that differ are usually a mistake.
Lists
Data Structures
A container for anything
A list is an all-encompassing construct that wraps together objects of all kinds under one name — a character vector, a numeric range and a logical value can sit side by side. Elements can be named; here the second one is.
junk <- list(c("black", "brown"), e2=22:28, TRUE)
junk## [[1]]
## [1] "black" "brown"
##
## $e2
## [1] 22 23 24 25 26 27 28
##
## [[3]]
## [1] TRUEUnnamed elements print as [[1]], [[3]]; the named one prints as $e2. The elements of a list can themselves be lists.
Three ways to reach inside
junk[[2]]## [1] 22 23 24 25 26 27 28junk$e2## [1] 22 23 24 25 26 27 28By position with [[ ]], or by name with $ when a name exists. Both hand you the vector 22:28, ready to use in arithmetic.
junk[2]## [[1]]
## [1] 22 23 24 25 26 27 28Single brackets return a list of one element, not the element. Notice the [[1]] wrapper in the output. This is the classic list mistake: if arithmetic on a list element fails, you probably used one bracket where you needed two.
What that failure looks like: junk[2] + 1 stops with Error in junk[2] + 1 : non-numeric argument to binary operator, while junk[[2]] + 1 returns 23 24 25 26 27 28 29. A name that does not exist is quieter: junk$e3 returns NULL with no message at all, so check spelling when a result is unexpectedly NULL.
Matrices
Data Structures
Two dimensions, one type
A matrix is a two-dimensional data structure. Like a vector, it must contain objects of the same type. Create an empty one by filling it with NA (missing) and stating the rows and columns.
mat <- matrix(NA, nrow = 4, ncol = 5)
mat## [,1] [,2] [,3] [,4] [,5]
## [1,] NA NA NA NA NA
## [2,] NA NA NA NA NA
## [3,] NA NA NA NA NA
## [4,] NA NA NA NA NAmat[r, ]= row r — the comma is required because the matrix has two dimensionsmat[ , c]= column c — comma firstmat[r, c]= the single element in row r, column c
Read it as mat[rows, columns]. Leaving a side empty means “all of them”.
mat[1,] <- c(2,3,7,5,8)
mat[2,] <- rep(4, 5)
mat[3,] <- 33:37
mat[4,] <- seq(23, 31, 2)
mat## [,1] [,2] [,3] [,4] [,5]
## [1,] 2 3 7 5 8
## [2,] 4 4 4 4 4
## [3,] 33 34 35 36 37
## [4,] 23 25 27 29 31All four rows are assigned vectors of length 5 because the matrix has 5 columns. rep(), : and seq() are explained on the Vectors tab. A row of the wrong length is an error: mat[1,] <- 1:3 gives Error in mat[1, ] <- 1:3 : number of items to replace is not a multiple of replacement length. To fill a matrix from one vector in a single call, matrix(1:20, nrow = 4) fills down the columns first; add byrow = TRUE to fill across the rows, which is what most people expect.
Names and lookups
rownames() and colnames()rownames(mat) <- c("r1", "r2", "r3", "r4")
rownames(mat)## [1] "r1" "r2" "r3" "r4"Assigning to rownames(mat) labels the rows; colnames() works the same way for columns.
mat[2,]## [1] 4 4 4 4 4mat[,3]## [1] 7 4 35 27mat[4,5]## [1] 31The second row, the third column, and the element in the fourth row and fifth column.
Two slips to recognise. mat[5, ] gives Error in mat[5, ] : subscript out of bounds because there are only four rows. mat[2] with no comma does not fail: it returns the single value 4, the second element counting down the first column, because a matrix is stored column by column. If you meant a row or a column, the comma is missing. Rows can also be fetched by the names you set: mat["r2", ].
Data Frames and Arrays
Data Structures
Data frame
A data frame is a restricted form of list with matrix-like features: its elements are columns, vectors of the same length, but they have names and can be of different types. Data sets for statistical modeling are almost always data frames, and every test and model on this sheet takes one.
df <- data.frame(haircolor = c("red", "black", "blonde"),
eyecolor = c("green", "brown", "blue"),
age = c(22, 23, 25),
phd = c(T, T, F))
df## haircolor eyecolor age phd
## 1 red green 22 TRUE
## 2 black brown 23 TRUE
## 3 blonde blue 25 FALSEThree rows and 4 columns; the columns are different variables. T and F are shorthand for TRUE and FALSE.
df$age## [1] 22 23 25df is the data frame and age the column. df$age is a plain vector, so mean(df$age) works. Every cars$mpg on the later tabs is this same idea.
df[3,]## haircolor eyecolor age phd
## 3 blonde blue 25 FALSEdf[,2]## [1] green brown blue
## Levels: blue brown greendf[3,3]## [1] 25The third row, the second column, and the single element at row 3, column 3. The Levels line appears because character columns were stored as factors (categories) in older R; it lists the categories present.
df$Age—NULL, silently: column names are case-sensitive and a wrong name is not an error.names(df)prints the exact spellings.df[, 5]—Error in `[.data.frame`(df, , 5) : undefined columns selected: there are only four columns.mean(df$haircolor)—NAwithWarning message: argument is not numeric or logical: returning NA. A text or factor column has no mean;table(df$haircolor)counts its categories instead.
Array
An array is a data structure with 2 or more dimensions — a matrix is the 2-dimensional case. The first argument is the vector of values, the second the dimensions.
my_arr <- array(1:8, c(2,2,2))
my_arr## , , 1
##
## [,1] [,2]
## [1,] 1 3
## [2,] 2 4
##
## , , 2
##
## [,1] [,2]
## [1,] 5 7
## [2,] 6 8The values 1 to 8 fill two 2×2 matrices, down each column first. The dimension vector reads: rows, columns, number of matrices.
my_arr[,,1]## [,1] [,2]
## [1,] 1 3
## [2,] 2 4my_arr[1,,1]## [1] 1 3my_arr[,1,1]## [1] 1 2The first matrix; the first row of the first matrix; the first column of the first matrix. Same rule as a matrix with one more comma.
Which structure?
| Structure | Dimensions | Types | Typical use |
|---|---|---|---|
| Vector | 1 | one type | a single variable, a column, a list of values |
| List | 1 | anything | bundling results; what most R functions return |
| Matrix | 2 | one type | numeric tables, contingency tables for chisq.test() |
| Data frame | 2 | one type per column | a data set: rows are observations, columns are variables |
| Array | 2 or more | one type | stacked matrices, as in the power-curve code |
Importing Data in RStudio
Data In and Out
The built-in Import Dataset tool
Probably the easiest way to import data is the module built into RStudio: it takes care of the details and, when you are new to R, it is the recommended route. The example below imports Cars.csv, the data set used on the rest of this sheet (available from the Purdue SCS site at www.stat.purdue.edu/scs/help/Intro_stat_software.html). Put it in your working directory first.
Click Import Dataset in the Environment panel (top right). The importers are grouped into three categories: text data, Excel data and statistical data (SPSS, SAS, Stata). A .csv is text data.

Choose the file and a pop-up window appears with a preview of the raw file on top and the data frame it will become below.

Under Name, give the data frame a name; the default is the file name without its extension. Then say whether the file has a headings row. Be careful when the preview looks like this — the column names are V1, V2, … and the real headings sit in row 1:

Change Heading to Yes and the file loads properly, with mpg, engine, horse, … as column names. The importer also handles the missing values, which are coded NA in this file.

The importer writes the matching read.csv() or read.table() command into the console as it runs. Copy that line into your script and you never have to click through the dialog again — see the next tab.
read.table and write.table
Data In and Out
Reading a delimited text file
read.table() reads any type of delimited ASCII file. It works the same way as the Import Dataset tool — in fact, the tool just translates your choices into this function call. Here is the Cars.csv file again:
cars <- read.table(file = "Cars.csv", header = TRUE, sep = ",")The data are stored as a data frame and assigned to cars on the left of the <-. The three most important arguments:
| Argument | Meaning | Default |
|---|---|---|
file | the file location; with no path, R looks in the current working directory, so give the full path or keep the file there | — |
header | whether the first row is a header row | FALSE |
sep | the separator between values: a comma for .csv, "\t" for tab-delimited | a blank space |
read.csv()cars <- read.csv("Cars.csv")read.csv() is read.table() with header = TRUE and sep = "," already set. The ANOVA tab uses it.
admission <- read.csv("https://stats.idre.ucla.edu/stat/data/binary.csv")The logistic-regression example imports its data remotely this way; no download step is needed.
- The file cannot be found —
Error in file(file, "rt") : cannot open the connectionfollowed byWarning message: cannot open file 'Cars.csv': No such file or directory. R looked in the working directory;getwd()shows which folder that is. Either move the file there, set the folder withsetwd("C:/Users/you/Documents")(forward slashes, even on Windows; in RStudio, Session → Set Working Directory), or give the full path infile =. headerleft atFALSE— no error, but the columns are namedV1,V2, …, the real headings become the first row of data, and every column is text.str(cars)shows it immediately; re-read withheader = TRUE.- Wrong
sep— a .csv read with the default blank-space separator comes in as one column whose name contains commas. Usesep = ","orread.csv().
Exporting a data frame
write.table() outputs a data frame to a file. Suppose we changed cars and want to save the result:
write.table(cars, file = "Cars2.csv", sep = "\t", row.names = FALSE,
col.names = TRUE)| Argument | Meaning | Default |
|---|---|---|
| first argument | the data frame to export | — |
file | the path of the file to be created | — |
sep | the separator; here a tab | a blank space |
row.names, col.names | whether the row names and column names appear in the file | both TRUE |
Row names in a data frame are usually just 1, 2, 3, …, which is why row.names = FALSE is the common choice. For a true comma-separated file use the shortcut write.csv(cars, "Cars2.csv", row.names = FALSE); the call above writes tabs into a file named .csv, which opens as a single column in Excel. Whatever you write, read it back with head(read.csv("Cars2.csv")) once to confirm the separator and headings survived.
Basic Statistics
Data In and Out
The Cars data
The commands below are the ones used most to explore and describe a data set. Cars.csv has 406 cars with mpg, engine displacement, horsepower, weight, acceleration, model year, origin (1, 2 or 3), cylinders, a filter column and a second mpg measurement, mpg1. Some rows contain NA, so the missing values are removed first:
cars = cars[-which(is.na(cars), arr.ind = T), ]is.na(cars) flags every missing cell, which(..., arr.ind = T) turns the flags into row-and-column positions, and the minus sign drops those rows. 379 complete rows remain.
This idiom has a trap: if the data frame contains no missing values at all, which() returns an empty index, and cars[-integer(0), ] keeps zero rows instead of all of them. Run it once, never twice, and check nrow(cars) afterwards. The safer spellings are cars <- na.omit(cars) or cars <- cars[complete.cases(cars), ], which do the same thing and are harmless when nothing is missing. colSums(is.na(cars)) shows how many NAs each column had before you drop anything.
Summary of statistics
# summary(dataset/variable)
summary(cars)## mpg engine horse weight
## Min. :10.00 Min. : 68.0 Min. : 46.0 Min. :1613
## 1st Qu.:17.50 1st Qu.:105.0 1st Qu.: 75.0 1st Qu.:2220
## Median :23.00 Median :151.0 Median : 92.0 Median :2790
## Mean :23.64 Mean :193.6 Mean :103.4 Mean :2958
## 3rd Qu.:29.00 3rd Qu.:261.0 3rd Qu.:123.5 3rd Qu.:3590
## Max. :46.60 Max. :455.0 Max. :230.0 Max. :5140
## accel year origin cylinder
## Min. : 8.00 Min. :70.00 Min. :1.000 Min. :4.000
## 1st Qu.:14.00 1st Qu.:73.00 1st Qu.:1.000 1st Qu.:4.000
## Median :15.50 Median :76.00 Median :1.000 Median :4.000
## Mean :15.57 Mean :76.03 Mean :1.567 Mean :5.462
## 3rd Qu.:17.05 3rd Qu.:79.00 3rd Qu.:2.000 3rd Qu.:8.000
## Max. :24.80 Max. :82.00 Max. :3.000 Max. :8.000
## filter_. mpg1
## Min. :0.0000 Min. :10.63
## 1st Qu.:0.0000 1st Qu.:17.16
## Median :1.0000 Median :22.71
## Mean :0.7441 Mean :23.58
## 3rd Qu.:1.0000 3rd Qu.:29.34
## Max. :1.0000 Max. :47.93Five-number summary plus the mean for every column. summary(cars$mpg) does one variable. Read it as a data check as much as a description: a Max. of 5140 for weight is plausible, a weight of 0 would not be; a column that is really a category (origin, cylinder) gets a meaningless mean here and should become a factor, after which summary() prints a count per level instead; and if any NA remained, an extra NA's line appears under that column.
Data structure
str()# str(dataset/variable)
str(cars)## 'data.frame': 379 obs. of 10 variables:
## $ mpg : num 10 11 11 11 12 12 12 13 13 13 ...
## $ engine : num 360 318 429 400 455 400 350 400 400 350 ...
## $ horse : int 215 210 208 150 225 167 180 170 175 165 ...
## $ weight : int 4615 4382 4633 4997 4951 4906 4499 4746 5140 ...
## $ accel : num 14 13.5 11 14 11 12.5 12.5 12 12 12 ...
## $ year : int 70 70 72 73 73 73 73 71 71 72 ...
## $ origin : int 1 1 1 1 1 1 1 1 1 1 ...
## $ cylinder: int 8 8 8 8 8 8 8 8 8 8 ...
## $ filter_.: int 0 0 0 0 0 0 0 0 0 0 ...
## $ mpg1 : num 10.9 12.1 10.6 10.8 12.3 ...379 observations of 10 variables, with each column’s type (num, int) and first values. Check this before modeling: a category stored as int (origin, cylinder) needs as.factor() before ANOVA.
Center, spread and position
# mean(variable, na.rm = TRUE)
mean(cars$mpg)## [1] 23.64248# var(variable)
var(cars$mpg)## [1] 59.8734# length(variable)
length(cars$mpg)## [1] 379sd(cars$mpg) gives the standard deviation, the square root of the variance.
# median(variable, na.rm = T)
median(cars$mpg)## [1] 23# quantile(variable, level, na.rm = T)
quantile(cars$mpg, 0.25)## 25%
## 17.5The argument na.rm = TRUE removes any NA and NaN values before computing; without it a single missing value makes the answer NA. quantile(cars$mpg, c(0.25, 0.5, 0.75)) returns all three quartiles at once.
t-Tests
Hypothesis Testing
One function, four tests
All of the t-tests on the Statistics Formula Sheet run through t.test(). Its arguments and their defaults:
t.test(x, y = NULL,
alternative = c("two.sided", "less", "greater"),
mu = 0, paired = FALSE, var.equal = FALSE,
conf.level = 0.95, ...)| Argument | Meaning | Default |
|---|---|---|
x, y | the sample(s); leave y out for a one-sample test | y = NULL |
alternative | two-sided, or one-sided "less" / "greater" | two-sided |
mu | the mean (or difference) under the null hypothesis | 0 |
paired | treat x and y as paired measurements | FALSE |
var.equal | assume equal variances (pooled test) instead of Welch | FALSE |
conf.level | level of the confidence interval in the output | 0.95 |
The four tests on the Cars data
# t.test(variable, mean under null hypothesis)
t.test(cars$mpg, mu = 25)##
## One Sample t-test
##
## data: cars$mpg
## t = -3.4155, df = 378, p-value = 0.0007058
## alternative hypothesis: true mean is not equal to 25
## 95 percent confidence interval:
## 22.86096 24.42400
## sample estimates:
## mean of x
## 23.64248t = −3.42 with df = n − 1 = 378 and p = 0.0007: reject H0: μ = 25. The interval (22.86, 24.42) excludes 25, which says the same thing.
# t.test(variable1, variable2)
t.test(cars$mpg, cars$mpg1)##
## Welch Two Sample t-test
##
## data: cars$mpg and cars$mpg1
## t = 0.10196, df = 755.88, p-value = 0.9188
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -1.052830 1.168186
## sample estimates:
## mean of x mean of y
## 23.64248 23.58480With var.equal left at its default R runs Welch’s test; note the fractional df = 755.88. p = 0.92: no evidence the two mpg measurements differ.
# t.test(variable1, variable2, var.equal = TRUE)
t.test(cars$mpg, cars$mpg1, var.equal = T)##
## Two Sample t-test
##
## data: cars$mpg and cars$mpg1
## t = 0.10196, df = 756, p-value = 0.9188
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -1.052830 1.168186
## sample estimates:
## mean of x mean of y
## 23.64248 23.58480Now df = n1 + n2 − 2 = 756. With equal sample sizes and similar spreads, pooled and Welch agree almost exactly — the F-test for variances on the formula sheet is what justifies this version.
# t.test(variable1, variable2, paired = TRUE)
t.test(cars$mpg, cars$mpg1, paired = T)##
## Paired t-test
##
## data: cars$mpg and cars$mpg1
## t = 1.0662, df = 378, p-value = 0.287
## alternative hypothesis: true difference in means is not equal to 0
## 95 percent confidence interval:
## -0.0486872 0.1640434
## sample estimates:
## mean of the differences
## 0.0576781mpg and mpg1 are two measurements on the same cars, so this is the right test of the three. It works on the 379 differences (df = 378); the interval is far narrower than the independent versions because car-to-car variation cancels out.
Reading any test output
- data: — which variables went in
- t, df, p-value — the statistic, its degrees of freedom and the p-value; compare p with α = 0.05
- alternative hypothesis — confirms the direction R tested
- confidence interval — for the mean (one-sample) or the difference; does it contain the null value?
- sample estimates — the mean(s) or mean difference the test is based on
Two groups stored in one column with a grouping variable beside them use the formula form: t.test(mpg ~ filter_., data = cars) compares the mpg of the filter = 0 cars with the filter = 1 cars. The grouping column must have exactly two values.
t.test(mpg ~ origin, data = cars)—Error in t.test.formula(mpg ~ origin, data = cars) : grouping factor must have exactly 2 levels. origin has three; three or more groups is a one-way ANOVA (its own tab).t.test(cars$mpg, 25)—Error in t.test.default(cars$mpg, 25) : not enough 'y' observations. Withoutmu =, the 25 is taken as a second sample of one value. Writemu = 25.- Welch when you meant pooled — not an error, but the output heading says Welch Two Sample t-test and df is fractional. Add
var.equal = TRUEif the formula sheet’s pooled test is what the question asks for.
Chi-Squared Test
Hypothesis Testing
A two-way table
Cars.csv does not lend itself to a chi-squared test, so this example uses a made-up two-way contingency table. The two factors are Degree (High, Low) and clinic (five levels from Worse to Marked Improvement); the cells hold counts.
chisq.test()y1 <- c(1,13,16,15,7)
y2 <- c(11,53,42,27,11)
y <- cbind(y1,y2)
dimnames(y) <- list(clinic = c("Worse","Stationary","Slight Improvement",
"Moderate Improvement","Marked Improvement"),
Degree = c("High","Low"))
y## Degree
## clinic High Low
## Worse 1 11
## Stationary 13 53
## Slight Improvement 16 42
## Moderate Improvement 15 27
## Marked Improvement 7 11cbind() binds the two vectors as columns of a matrix; dimnames() names the rows and columns so the output reads like a table.
When the data are raw observations rather than counts, let R build the table: table(cars$origin, cars$cylinder) cross-tabulates two columns, and chisq.test(table(cars$origin, cars$cylinder)) tests them; chisq.test(cars$origin, cars$cylinder) with the two columns as x and y does the same in one step. For a 2 × 2 table R applies Yates’ continuity correction by default; correct = FALSE gives the uncorrected statistic on the formula sheet. Passing percentages instead of counts is the mistake to avoid: the test needs the raw frequencies.
chi.test <- chisq.test(y)
chi.test## Warning in chisq.test(y): Chi-squared approximation may be incorrect
##
## Pearson's Chi-squared test
##
## data: y
## X-squared = 6.8807, df = 4, p-value = 0.1423χ² = 6.88 with df = (5 − 1)(2 − 1) = 4 and p = 0.14: no evidence that improvement depends on degree. The warning appears because an expected count is below 5 (the Worse/High cell, 3.18) — the condition on the formula sheet.
What else the test object holds
names()names(chi.test)## [1] "statistic" "parameter" "p.value" "method" "data.name" "observed"
## [7] "expected" "residuals" "stdres"A test result is a list (Data Structures tab). Each part is reachable with $: chi.test$p.value returns just the p-value, handy inside a script.
$expectedchi.test$expected## Degree
## clinic High Low
## Worse 3.183673 8.816327
## Stationary 17.510204 48.489796
## Slight Improvement 15.387755 42.612245
## Moderate Improvement 11.142857 30.857143
## Marked Improvement 4.775510 13.224490E = (row total × column total) ⁄ grand total for each cell. Two cells are below 5, which is what triggered the warning above.
Correlation and Scatterplots
Hypothesis Testing
Correlation coefficient
The default form of cor() and its options:
cor(x, y = NULL, use = "everything",
method = c("pearson", "kendall", "spearman"))
# by default it uses the Pearson methodx and y are two numeric vectors of the same length; give a whole data frame of numeric columns as x alone and cor() returns the matrix of every pairwise correlation. use says what to do with missing values: the default "everything" returns NA as soon as either vector contains an NA, which is why the missing rows were removed on the Basic Statistics tab; use = "complete.obs" drops incomplete pairs instead. method picks Pearson (linear), Spearman (ranks) or Kendall (concordant pairs); only the first letter of the chosen name is required to be exact, but write the whole word.
# cor(variable1, variable2)
cor(cars$mpg, cars$engine)## [1] -0.812826Strong negative linear relationship: bigger engines, lower mpg.
cor(cars$mpg, cars$engine, method = "spearman")## [1] -0.8729739Spearman is even stronger here, a hint that the relationship is monotonic but curved rather than a straight line — look at the scatterplot below.
Correlation significance test
# cor.test(variable1, variable2)
cor.test(cars$mpg, cars$engine)##
## Pearson's product-moment correlation
##
## data: cars$mpg and cars$engine
## t = -27.094, df = 377, p-value < 2.2e-16
## alternative hypothesis: true correlation is not equal to 0
## 95 percent confidence interval:
## -0.8444198 -0.7755971
## sample estimates:
## cor
## -0.812826t = r√(n − 2) ⁄ √(1 − r²) = −27.1 with df = 377. p < 2.2e-16 is R’s way of printing a p-value smaller than it can represent.
cor.test(cars$mpg, cars$engine, method = "spearman")##
## Spearman's rank correlation rho
##
## data: cars$mpg and cars$engine
## S = 16994000, p-value < 2.2e-16
## alternative hypothesis: true rho is not equal to 0
## sample estimates:
## rho
## -0.8729739
##
## Warning in cor.test.default(cars$mpg, cars$engine, method = "spearman"):
## Cannot compute exact p-value with tiesThe warning is harmless: with tied ranks R uses an approximation for the p-value instead of the exact one.
Plotting a scatterplot
plot(cars$mpg, cars$engine, xlab = "Miles Per Gallon", ylab = "Engine Displacement",
main = "Scatterplot between Miles Per Gallon & Engine Displacement")
plot(x, y) with xlab, ylab and main for the axis titles and the plot title.The first argument goes on the x-axis, the second on the y-axis. The curve in the cloud is why Spearman beat Pearson above.
One-Way ANOVA
Hypothesis Testing
Set up: a factor and a response
The response is mpg and the factor is origin, which has three levels: 1, 2 and 3. Because origin is stored as a number, convert it to a factor (categorical variable) first or R will fit a regression line through 1, 2, 3 instead of comparing three groups.
as.factor()# Import a csv file using read.csv()
cars <- read.csv("Cars.csv")
cars$origin <- as.factor(cars$origin)
levels(cars$origin)## [1] "1" "2" "3"levels() confirms the three groups.
plot(mpg ~ origin, data = cars, pch = 16, cex = 0.4)
plot() draw boxplots.The median mpg of origin 1 is lower than origins 2 and 3. In the call, pch = 16 draws the outlier points as solid dots and cex = 0.4 shrinks them to 40% size; both are optional and work in every base plot.
Fit and test
aov()summary()results = aov(mpg ~ origin, data = cars)Modeling functions such as aov() and lm() take a model formula of the form y ~ x1*x2 + x3 and a data = argument naming the data frame; inside the formula the columns are referred to simply as mpg and origin. The fitted model stored in results is a list that is unreadable on its own; functions called methods, like summary() and plot(), extract what you need.
summary(results)## Df Sum Sq Mean Sq F value Pr(>F)
## origin 2 7985 3992 97.97 <2e-16 ***
## Residuals 394 16056 41
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 9 observations deleted due to missingnessF = MSB ⁄ MSW = 3992 ⁄ 41 = 97.97 with df (2, 394) and p < 2e-16: reject the hypothesis that the mean mpg is the same for all three origins. The rows are the Between (origin) and Within (Residuals) lines of the formula sheet’s ANOVA table.
The tell-tale of a forgotten as.factor(): the origin row shows Df 1 instead of 2, because R fitted a single straight-line slope through the codes 1, 2, 3 rather than comparing three groups. The number of groups minus one is always the Df of a factor; if it is wrong, go back to the conversion step. A second common error is running TukeyHSD() on a model fitted with lm(): Error in UseMethod("TukeyHSD") : no applicable method for 'TukeyHSD' applied to an object of class "lm". Tukey needs the aov() fit.
Multiple comparisons
A significant F says some means differ. Pairwise comparisons, with a correction for testing several pairs, say which ones.
pairwise.t.test()pairwise.t.test(cars$mpg, cars$origin, p.adjust = "bonferroni")##
## Pairwise comparisons using t tests with pooled SD
##
## data: cars$mpg and cars$origin
##
## 1 2
## 2 <2e-16 -
## 3 <2e-16 0.045
##
## P value adjustment method: bonferroniEach cell is an adjusted p-value for one pair. All three are below 0.05, so the mean mpg differs between every pair of origins.
TukeyHSD()results = aov(mpg ~ origin, data = cars)
TukeyHSD(results, conf.level = 0.95)## Tukey multiple comparisons of means
## 95% family-wise confidence level
##
## Fit: aov(formula = mpg ~ origin, data = cars)
##
## $origin
## diff lwr upr p adj
## 2-1 7.763203 5.73054715 9.795858 0.0000000
## 3-1 10.322407 8.38214860 12.262666 0.0000000
## 3-2 2.559204 0.09398439 5.024424 0.0397888Tukey gives a confidence interval for each difference in means. None of the three intervals contains 0, so all three differences are significant — the same conclusion.
Model diagnostics
plot(results, pch = 16, cex = 0.4)Calling plot() on a fitted model draws the four standard diagnostic plots, one at a time (press Return in the console to step through them).

One vertical band per group, centered on zero. The red line connects the medians of the different groups; flat means the model is fine.

Most of the standardized residuals follow the straight line, but a few drift away at the beginning and the end, which suggests the distribution of residuals is a little skewed.

Checks equal variance across groups: the three bands should be about the same height.

Looks for influential observations. With a one-factor model all points in a group share the same leverage, so the plot is three columns; nothing crosses the Cook’s distance contours.
Linear Regression
Regression
Fit everything
As before, remove the missing values first and list the variable names. In a formula a lone dot means every other column, so mpg ~ . regresses mpg on all nine remaining variables.
cars <- cars[-which(is.na(cars), arr.ind = T), ]
names(cars)## [1] "mpg" "engine" "horse" "weight" "accel" "year"
## [7] "origin" "cylinder" "filter_." "mpg1"mod.reg <- lm(mpg ~ ., data = cars)
summary(mod.reg)##
## Call:
## lm(formula = mpg ~ ., data = cars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -3.3196 -0.6958 0.0189 0.6254 3.0243
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.5673545 1.5809687 -0.359 0.71990
## engine 0.0025929 0.0024279 1.068 0.28622
## horse 0.0004493 0.0046635 0.096 0.92330
## weight -0.0006067 0.0002320 -2.615 0.00930 **
## accel 0.0159285 0.0316724 0.503 0.61533
## year 0.0662729 0.0200110 3.312 0.00102 **
## origin 0.0964715 0.0902488 1.069 0.28579
## cylinder -0.2033509 0.1193718 -1.704 0.08931 .
## filter_. -0.4577229 0.2929970 -1.562 0.11910
## mpg1 0.9102985 0.0167311 54.407 < 2e-16 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 1.023 on 369 degrees of freedom
## Multiple R-squared: 0.9829, Adjusted R-squared: 0.9825
## F-statistic: 2362 on 9 and 369 DF, p-value: < 2.2e-16- Estimate — the slope bj: the change in mpg per unit of that predictor with the others held fixed
- Std. Error — SE of the slope
- t value — Estimate ⁄ Std. Error, with df = n − k − 1 = 369
- Pr(>|t|) — the two-sided p-value for H0: βj = 0
- stars — significance codes: *** below 0.001, ** below 0.01, * below 0.05, . below 0.1
Here mpg1 dominates (it is a second measurement of the same thing) and weight and year are the only other significant predictors. Leaving out data = cars is the usual first error: lm(mpg ~ engine) stops with Error in eval(predvars, data, env) : object 'mpg' not found, because the bare column names exist only inside the data frame.
- Residual standard error — se = 1.023, the typical size of a residual
- Multiple R-squared — 0.9829: the model explains 98.3% of the variation in mpg
- Adjusted R-squared — 0.9825, penalized for the nine predictors
- F-statistic — 2362 on (9, 369) df, p < 2.2e-16: the overall test that at least one slope is non-zero
These are the quantities on the Multiple Regression tab of the formula sheet, in the order R prints them.
Choosing the predictors
mod1 <- lm(mpg ~ engine + horse + weight, data = cars)
summary(mod1)##
## Call:
## lm(formula = mpg ~ engine + horse + weight, data = cars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -9.4431 -2.7307 -0.3825 2.2516 16.1406
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 44.7774973 1.2369586 36.200 < 2e-16 ***
## engine -0.0098511 0.0069098 -1.426 0.1548
## horse -0.0278049 0.0133328 -2.085 0.0377 *
## weight -0.0055278 0.0007289 -7.584 2.67e-13 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 4.169 on 375 degrees of freedom
## Multiple R-squared: 0.7121, Adjusted R-squared: 0.7098
## F-statistic: 309.1 on 3 and 375 DF, p-value: < 2.2e-16Plus signs add predictors. Without mpg1 the model explains 71% of the variation; weight is by far the strongest predictor.
engine*horse# engine*horse in R indicates the main effects of engine and horse
# as well as their interaction effect.
mod2 <- lm(mpg ~ engine*horse + weight, data = cars)
summary(mod2)##
## Call:
## lm(formula = mpg ~ engine * horse + weight, data = cars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -9.936 -2.216 -0.238 1.871 16.781
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 5.373e+01 1.568e+00 34.278 < 2e-16 ***
## engine -7.268e-02 9.879e-03 -7.357 1.20e-12 ***
## horse -1.796e-01 2.201e-02 -8.161 5.11e-15 ***
## weight -2.895e-03 7.417e-04 -3.903 0.000113 ***
## engine:horse 4.724e-04 5.686e-05 8.308 1.81e-15 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.835 on 374 degrees of freedom
## Multiple R-squared: 0.7569, Adjusted R-squared: 0.7543
## F-statistic: 291.2 on 4 and 374 DF, p-value: < 2.2e-16The engine:horse row is the interaction: the effect of engine size depends on horsepower. Adjusted R² rises from 0.710 to 0.754, so the interaction earns its place.
(engine + horse + weight)^3mod3 <- lm(mpg ~ (engine + horse + weight)^3, data = cars)
summary(mod3)##
## Call:
## lm(formula = mpg ~ (engine + horse + weight)^3, data = cars)
##
## Residuals:
## Min 1Q Median 3Q Max
## -9.5411 -2.2346 -0.4175 1.7745 17.3233
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 6.163e+01 5.560e+00 11.085 < 2e-16 ***
## engine -1.208e-01 3.819e-02 -3.163 0.00169 **
## horse -1.871e-01 7.713e-02 -2.426 0.01573 *
## weight -6.913e-03 2.398e-03 -2.883 0.00417 **
## engine:horse 5.980e-04 2.627e-04 2.277 0.02338 *
## engine:weight 1.982e-05 9.870e-06 2.008 0.04541 *
## horse:weight 1.461e-05 2.680e-05 0.545 0.58582
## engine:horse:weight -7.848e-08 6.647e-08 -1.181 0.23848
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 3.817 on 371 degrees of freedom
## Multiple R-squared: 0.7612, Adjusted R-squared: 0.7567
## F-statistic: 169 on 7 and 371 DF, p-value: < 2.2e-16The ^3 expands to all main effects, all two-way interactions and the three-way interaction. The three-way term and horse:weight are not significant; adjusted R² barely moves. More terms is not better.
| Formula | Means |
|---|---|
y ~ x | simple regression of y on x |
y ~ x1 + x2 | main effects of x1 and x2 |
y ~ x1*x2 | x1 + x2 + their interaction x1:x2 |
y ~ x1:x2 | the interaction only |
y ~ (x1+x2+x3)^2 | all main effects and all two-way interactions |
y ~ . | y on every other column in the data |
y ~ x - 1 | drop the intercept |
The same notation drives aov(), glm() and lmer().
Pulling numbers out of a summary
names()sum = summary(mod.reg)
names(sum)## [1] "call" "terms" "residuals" "coefficients"
## [5] "aliased" "sigma" "df" "r.squared"
## [9] "adj.r.squared" "fstatistic" "cov.unscaled"A summary is a list, so each piece is available by name: sum$r.squared, sum$sigma (the residual standard error), sum$fstatistic.
$coefficientssum$coefficients## Estimate Std. Error t value Pr(>|t|)
## (Intercept) -0.5673545304 1.580968723 -0.35886512 7.199012e-01
## engine 0.0025929429 0.002427858 1.06799595 2.862205e-01
## horse 0.0004492931 0.004663497 0.09634253 9.233008e-01
## weight -0.0006066500 0.000232019 -2.61465725 9.297769e-03
## accel 0.0159284879 0.031672447 0.50291308 6.153254e-01
## year 0.0662728753 0.020011017 3.31181941 1.018461e-03
## origin 0.0964715379 0.090248782 1.06895114 2.857905e-01
## cylinder -0.2033509048 0.119371772 -1.70350915 8.931478e-02
## filter_. -0.4577229299 0.292996952 -1.56221055 1.190956e-01
## mpg1 0.9102985190 0.016731122 54.40749836 2.447556e-178# just the p-values: the fourth column
sum$coefficients[,4]## (Intercept) engine horse weight accel
## 7.199012e-01 2.862205e-01 9.233008e-01 9.297769e-03 6.153254e-01
## year origin cylinder filter_. mpg1
## 1.018461e-03 2.857905e-01 8.931478e-02 1.190956e-01 2.447556e-178The coefficient table is a matrix, so the matrix indexing from the Data Structures tab applies: [,4] is the fourth column, the p-values; ["weight", 1] would be the weight estimate.
Logistic Regression
Regression
A binary response
Suppose we want to know how GRE score, GPA and the prestige of the undergraduate institution affect admission to graduate school. The response admit is binary (1 = admitted, 0 = not), so linear regression is the wrong tool; logistic regression models the probability of admission through the log-odds.
read.csv() with a URLsummary()admission <- read.csv("https://stats.idre.ucla.edu/stat/data/binary.csv")
head(admission)## admit gre gpa rank
## 1 0 380 3.61 3
## 2 1 660 3.67 3
## 3 1 800 4.00 1
## 4 1 640 3.19 4
## 5 0 520 2.93 4
## 6 1 760 3.00 2head() shows the first six rows. Three predictors: gre and gpa are continuous; rank runs from 1 (highest prestige) to 4 (lowest).
summary(admission)## admit gre gpa rank
## Min. :0.0000 Min. :220.0 Min. :2.260 Min. :1.000
## 1st Qu.:0.0000 1st Qu.:520.0 1st Qu.:3.130 1st Qu.:2.000
## Median :0.0000 Median :580.0 Median :3.395 Median :2.000
## Mean :0.3175 Mean :587.7 Mean :3.390 Mean :2.485
## 3rd Qu.:1.0000 3rd Qu.:660.0 3rd Qu.:3.670 3rd Qu.:3.000
## Max. :1.0000 Max. :800.0 Max. :4.000 Max. :4.000The mean of a 0/1 variable is the proportion: 31.75% of the 400 applicants were admitted.
Fit with glm()
factor()admission$rank <- factor(admission$rank)
levels(admission$rank)## [1] "1" "2" "3" "4"Converting rank to a factor tells R to treat it as four categories rather than a number.
family = "binomial"results <- glm(admit ~ gre + gpa + rank, data = admission, family = "binomial")
summary(results)##
## Call:
## glm(formula = admit ~ gre + gpa + rank, family = "binomial",
## data = admission)
##
## Deviance Residuals:
## Min 1Q Median 3Q Max
## -1.5802 -0.8848 -0.6382 1.1575 2.1732
##
## Coefficients:
## Estimate Std. Error z value Pr(>|z|)
## (Intercept) -3.449548 1.132846 -3.045 0.00233 **
## gre 0.002294 0.001092 2.101 0.03564 *
## gpa 0.777014 0.327484 2.373 0.01766 *
## rank -0.560031 0.127137 -4.405 1.06e-05 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## (Dispersion parameter for binomial family taken to be 1)
##
## Null deviance: 499.98 on 399 degrees of freedom
## Residual deviance: 459.44 on 396 degrees of freedom
## AIC: 467.44
##
## Number of Fisher Scoring iterations: 4glm() is lm() for generalized linear models; family = "binomial" selects logistic regression. The coefficient table is read like a regression table, with z in place of t. gre, gpa and rank are all statistically significant.
Interpreting the coefficients
exp(coef())A logistic coefficient is the change in the log odds of the outcome for a one-unit increase in the predictor. Each extra GPA point raises the log-odds of admission by 0.777; each step down in prestige (rank 1 → 2) lowers it by 0.560.
The Null and Residual deviance play the role of SST and SSE: the drop from 499.98 to 459.44 on 3 df is the overall test of the model. AIC compares competing models (lower is better).
exp(coef(results))## (Intercept) gre gpa rank
## 0.03175998 1.00229659 2.17496718 0.57119114Exponentiating turns log-odds into odds ratios. The odds of admission multiply by 2.17 for each additional GPA point, by 1.0023 per GRE point, and by 0.57 for each step down in rank.
The tutorial’s version of this output treats rank as a single numeric slope. Because rank was converted to a factor, current R prints separate rows for rank2, rank3 and rank4 instead — each compared with rank 1. The interpretation is the same: lower prestige, lower odds.
What Power Is
Power Analysis
Definition
The power of a test is the probability of detecting an effect given that the effect exists — in statistical jargon, the probability of rejecting the null hypothesis when the alternative of interest is true. It is 1 − β, where β is the Type II error rate.
- To find the sample size needed to detect a given effect size at a specified power — done before data collection
- To find the power of the test given an effect size and the sample size available — used when the number of subjects is limited; a low power is a good reason to rethink whether to proceed
There is no golden rule for the minimum power, but larger is better because it reduces the risk of a Type II error. Scientists often follow Cohen (1988), Statistical Power Analysis for the Behavioral Sciences: design studies for a power of at least 0.8.
- Sample size — n (per group, for two-sample tests)
- Effect size — Cohen’s d for t-tests (difference in means ⁄ SD); f for ANOVA
- Significance level — α, the Type I error rate: the probability of finding an effect when none is present; usually 0.05
- Power — 1 − β: the probability of detecting an effect that is present
Given any three, the fourth can be computed. Leave the one you want empty in the function call.
The pwr package
library(pwr) # install.packages("pwr") the first time| Function | Test | Key arguments |
|---|---|---|
pwr.t.test() | one-sample, two-sample (equal n) or paired t-test | n, d, sig.level, power, type, alternative |
pwr.t2n.test() | two-sample t-test with unequal group sizes | n1, n2, d, sig.level, power |
pwr.anova.test() | balanced one-way ANOVA | k, n, f, sig.level, power |
pwr.p.test(), pwr.2p.test() | one- and two-proportion tests | h, n, sig.level, power |
pwr.chisq.test() | chi-squared tests | w, N, df, sig.level, power |
pwr.r.test() | correlation | r, n, sig.level, power |
Effect-size conventions from Cohen: d of 0.2, 0.5, 0.8 is small, medium, large; f of 0.1, 0.25, 0.4; r of 0.1, 0.3, 0.5.
Power for t-Tests
Power Analysis
One-sample t-test
The null hypothesis is that the mean equals a constant; the alternative may be right-tailed, left-tailed or two-tailed. In pwr.t.test() n is the total sample size, d the effect size, sig.level the significance level, power the power, and type = "one.sample" picks the test. Specify any three of n, d, sig.level and power and the fourth is returned.
pwr.t.test(n = , d = 0.40, sig.level = 0.05, power = 0.8,
type = "one.sample", alternative = "two.sided")##
## One-sample t test power calculation
##
## n = 51.00945
## d = 0.4
## sig.level = 0.05
## power = 0.8
## alternative = two.sidedA total of 51 subjects is required to achieve 80% power. Always round n up. The empty n = in the call is the tutorial’s way of writing n = NULL; either spelling works, and leaving the argument out entirely does the same. Exactly one of n, d, sig.level and power may be missing: supply all four and pwr.t.test() stops with Error in pwr.t.test(...) : exactly one of n, d, power, and sig.level must be NULL.
pwr.t.test(n = 30, d = 0.40, sig.level = 0.05, power = ,
type = "one.sample", alternative = "two.sided")##
## One-sample t test power calculation
##
## n = 30
## d = 0.4
## sig.level = 0.05
## power = 0.5628136
## alternative = two.sidedWith only 30 subjects the power is about 56%: a real effect of this size would be missed almost half the time.
Two-sample t-test
A two-sample t-test compares the means of two different groups and is only valid when the two groups are not correlated. Here we want 90% power to detect d = 0.6 at α = 0.05.
type = "two.sample"pwr.t2n.test()pwr.t.test(n = , d = 0.6, sig.level = 0.05, power = 0.9,
type = "two.sample", alternative = "two.sided")##
## Two-sample t test power calculation
##
## n = 59.35155
## d = 0.6
## sig.level = 0.05
## power = 0.9
## alternative = two.sided
##
## NOTE: n is number in *each* groupRead the NOTE: n is the number in each group, so 60 per group and 120 in total. Leave power empty instead to get the power for a known n.
pwr.t2n.test(n1 = 40, n2 = 57, d = 0.6, sig.level = 0.05, power = ,
alternative = "two.sided")##
## t test power calculation
##
## n1 = 40
## n2 = 57
## d = 0.6
## sig.level = 0.05
## power = 0.821067
## alternative = two.sidedWhen one group has more subjects than the other, pwr.t2n.test() takes both sizes. Power here is about 82%.
Paired t-test
A paired t-test compares two groups whose data are correlated — before and after an intervention on the same subjects, for example. Sample size for 90% power at α = 0.05 with a minimum effect size of 0.8:
pwr.t.test(n = , d = 0.8, sig.level = 0.05, power = 0.9,
type = "paired", alternative = "two.sided")##
## Paired t test power calculation
##
## n = 18.44623
## d = 0.8
## sig.level = 0.05
## power = 0.9
## alternative = two.sided
##
## NOTE: n is the number of *pairs*With 19 pairs (18.45 rounded up) we could achieve 90% power. For a paired test, d is the mean difference divided by the SD of the differences.
Power for ANOVA and Power Curves
Power Analysis
One-way ANOVA
Power analysis for a one-way ANOVA with k levels uses pwr.anova.test(). Here n is the number of subjects per level and f is the effect size. Sample size for 4 levels, 80% power and f = 0.4 at α = 0.05:
pwr.anova.test(k = 4, n = , f = 0.4, sig.level = 0.05, power = 0.8)##
## Balanced one-way analysis of variance power calculation
##
## k = 4
## n = 18.04262
## f = 0.4
## sig.level = 0.05
## power = 0.8
##
## NOTE: n is the number in each groupTo detect a treatment effect of f = 0.4 or larger with 80% power, each of the four groups needs 19 subjects (18.04 rounded up), so about 76 in total. Leave power empty to compute the power for a known per-group n; the groups must be the same size for this function.
Power curves
A power curve shows how the power of a test varies with sample size and effect size, and is usually a better way to explain the trade-off than a single number. The code below draws, for a one-way ANOVA with 4 equal groups at α = 0.05, the sample size needed across a range of effect sizes, one curve per target power. Read the comments to see what to change for another test.
Power-curve script
# The code generates a power curve for a One-Way ANOVA model with 4 levels of equal sample size.
# Step 1: Load the pwr package.
library(pwr)
# Step 2: Define the range of effect sizes for the curve with seq().
# Here the effect size runs from 0.1 to 0.6 in steps of 0.01.
f <- seq(.1, .6, .01)
nf <- length(f)
# Step 3: Define the range of powers acceptable for the study.
# Here power runs from 0.4 to 0.95 in steps of 0.1.
p <- seq(.4, .95, .1)
np <- length(p)
# Obtain the sample sizes.
samsize <- array(numeric(nf*np), dim = c(nf, np))
for (i in 1:np) {
for (j in 1:nf) {
# Swap in the power function for your own analysis here, for example
# pwr.t.test() for a one-sample t-test or pwr.t2n.test() for a two-sample t-test.
result <- pwr.anova.test(k = 4, n = , f = f[j], sig.level = .05, power = p[i])
samsize[j, i] <- ceiling(result$n)
}
}
# Set up the graph.
xrange <- range(f)
yrange <- round(range(samsize))
colors <- rainbow(length(p))
plot(xrange, yrange, type = "n",
xlab = "Effect size",
ylab = "Sample Size (n)")
# Add the power curves.
for (i in 1:np) {
lines(f, samsize[, i], type = "l", lwd = 2, col = colors[i])
}
# Add annotation: grid lines, title, legend.
abline(v = 0, h = seq(0, yrange[2], 50), lty = 2, col = "grey89")
abline(h = 0, v = seq(xrange[1], xrange[2], .02), lty = 2, col = "grey89")
title("Power curve for a One-way Anova, Sig=0.05")
legend("topright", title = "Power", as.character(p), fill = colors)
seq()— builds the grids of effect sizes and powersarray()— an nf × np table to hold the sample sizes (Data Structures tab)- the double
forloop — fills the table: one power analysis per (effect size, power) pair ceiling()— rounds each n up to a whole subjectplot(type = "n")— draws empty axes;lines()then adds one curve per powerabline()— dashed grey grid lineslegend()— labels the curves
- Replace
pwr.anova.test(k = 4, ...)with the function for your test, keepingn =empty and passing the effect size fromf[j]and the power fromp[i] - Change the effect-size range in
seq(.1, .6, .01)to match that test’s effect-size scale (d for t-tests) - Edit the title and axis labels
For a t-test the result is stored in result$n just the same, so nothing else changes.
Linear Mixed Models
Mixed Models
Fixed and random factors
One or more factors may be treated as random effects: their levels can be thought of as randomly sampled from a larger population of levels (classrooms drawn from all classrooms, batches from all batches). When a linear model has both fixed and random factors it is a linear mixed model (LMM). R fits them with the lme4 package and tests them with the car package.
read.csv() and head()dat = read.csv("Cars.csv")
head(dat, 10)## mpg engine horse weight accel year origin cylinder filter mpg1
## 1 9 4 93 732 8.5 0 NA NA NA 9.98
## 2 10 360 215 4615 14.0 70 1 8 0 10.87
## 3 10 307 200 4376 15.0 70 1 8 0 9.63
## 4 11 318 210 4382 13.5 70 1 8 0 12.12
## 5 11 429 208 4633 11.0 72 1 8 0 10.63
## 6 11 400 150 4997 14.0 73 1 8 0 10.79
## 7 11 350 180 3664 11.0 73 1 8 0 12.22
## 8 12 383 180 4955 11.5 71 1 8 0 12.11
## 9 12 350 160 4456 13.5 72 1 8 0 12.66
## 10 12 429 198 4952 11.5 73 1 8 0 11.68head(dat, 10) shows the first ten rows. The first car has NA for origin, cylinder and filter.
lmer()dat$origin = as.factor(dat$origin)
dat$cylinder = as.factor(dat$cylinder)
dat$filter = as.factor(dat$filter)origin, cylinder and filter are categorical, so each is converted with as.factor().
library(lme4) # install.packages("lme4")
model = lmer(mpg1 ~ origin + (1 | cylinder), data = dat, REML = FALSE)## Loading required package: MatrixResponse mpg1, origin as the fixed factor, cylinder as the random factor. Building an LMM is like lm() except that random terms are declared in parentheses: (1 | cylinder) means a random intercept for each cylinder level.
REML chooses between maximum likelihood (ML) and restricted maximum likelihood (REML). REML = FALSE uses ML, which is what you need to compare models with different fixed effects.
If the fit prints boundary (singular) fit: see help('isSingular'), the model ran but estimated a random-effect variance as exactly 0: the groups are not detectably different, or there are too few of them (cylinder has only five levels here). It is a message to think about, not an error to fix; with very few levels, treating the factor as fixed is often the honest choice.
Reading the summary
summary(model)## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: mpg1 ~ origin + (1 | cylinder)
## Data: dat
##
## AIC BIC logLik deviance df.resid
## 2373.4 2393.3 -1181.7 2363.4 392
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -2.4654 -0.6018 -0.1019 0.4598 3.9633
##
## Random effects:
## Groups Name Variance Std.Dev.
## cylinder (Intercept) 24.22 4.921
## Residual 21.54 4.642
## Number of obs: 397, groups: cylinder, 5
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 20.8890 2.3251 8.984
## origin2 0.7503 0.7459 1.006
## origin3 3.9086 0.7173 5.449
##
## Correlation of Fixed Effects:
## (Intr) orign2
## origin2 -0.115
## origin3 -0.117 0.437The estimated standard deviation of the random factor cylinder is 4.921 and the residual standard deviation is 4.642: cylinder-to-cylinder differences are about as large as the car-to-car noise within a cylinder group. Five cylinder levels, 397 observations.
origin = 1 is the baseline level; origin2 and origin3 are the differences from it (+0.75 and +3.91 mpg). lme4 deliberately prints t values without p-values — the degrees of freedom for a mixed model are not well defined. The next tab shows how to get a test.
Significance and Nested Factors
Mixed Models
Significance test
The lme4 package does not compute p-values for fixed effects. The Anova() function in the car package does, with a Type II Wald chi-squared test:
library(car) # install.packages("car")
Anova(model)## Analysis of Deviance Table (Type II Wald chisquare tests)
##
## Response: mpg1
## Chisq Df Pr(>Chisq)
## origin 32.038 2 1.104e-07 ***
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1χ² = 32.04 on 2 df, p = 1.1e-07: origin has a significant effect on mpg1. Note the capital A — Anova() from car, not base R’s anova().
Nested factors
A random factor g2 nested in a fixed factor g1 is written g1 + (1 | g1:g2). If g1 is also random, it is (1 | g1) + (1 | g1:g2), which can be shortened to (1 | g1/g2). Here filter is treated as a fixed factor and cylinder is nested in filter:
(1 | filter:cylinder)model2 = lmer(mpg1 ~ origin + filter + (1 | filter:cylinder),
data = dat, REML = FALSE)
summary(model2)## Linear mixed model fit by maximum likelihood ['lmerMod']
## Formula: mpg1 ~ origin + filter + (1 | filter:cylinder)
## Data: dat
##
## AIC BIC logLik deviance df.resid
## 2326.5 2350.3 -1157.3 2314.5 384
##
## Scaled residuals:
## Min 1Q Median 3Q Max
## -2.4593 -0.5981 -0.1003 0.4635 3.9561
##
## Random effects:
## Groups Name Variance Std.Dev.
## filter:cylinder (Intercept) 10.80 3.287
## Residual 21.44 4.630
## Number of obs: 390, groups: filter:cylinder, 3
##
## Fixed effects:
## Estimate Std. Error t value
## (Intercept) 14.8941 3.3184 4.488
## origin2 0.7022 0.7473 0.940
## origin3 3.9518 0.7184 5.501
## filter1 8.7999 4.0693 2.163
##
## Correlation of Fixed Effects:
## (Intr) orign2 orign3
## origin2 0.000
## origin3 0.000 0.436
## filter1 -0.815 -0.049 -0.051The random term is now the cylinder-within-filter combination (3 groups). Part of the cylinder variance (24.2 before) has moved into the fixed filter effect, leaving 10.8.
Anova(model2)Anova(model2)## Analysis of Deviance Table (Type II Wald chisquare tests)
##
## Response: mpg1
## Chisq Df Pr(>Chisq)
## origin 32.8924 2 7.203e-08 ***
## filter 4.6764 1 0.03058 *
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1Both fixed factors are significant: origin strongly, filter at the 0.05 level.
| Term | Meaning |
|---|---|
(1 | g) | random intercept for each level of g |
(1 | g1:g2) | random intercept for each g1–g2 combination (g2 nested in g1) |
(1 | g1/g2) | shorthand for (1 | g1) + (1 | g1:g2) |
(x | g) | random intercept and random slope of x for each g |
Graphics and Resources
The base plotting functions and where to go next
Create a plot
Base R draws a graph with one function call. set.seed() fixes the random-number generator so that rnorm(100) — 100 draws from a standard normal distribution — gives the same numbers every time.
hist()set.seed(1)
hist(rnorm(100))Bell-shaped around 0 with most values between −2 and 2, as a standard normal sample should be. The title and axis label are generated from the expression you plotted. hist(x, breaks = 20) asks for about 20 bars instead of R’s choice; hist(cars$mpg, main = "Miles per gallon", xlab = "mpg", col = "grey") replaces the generated labels. Because rnorm() is random, omit set.seed(1) and the bars change every run.

Base graphics used on this sheet
| Function | Draws | Where it appears |
|---|---|---|
hist(x) | a histogram of one variable | above |
plot(x, y) | a scatterplot of y against x | Correlation and Scatterplots |
plot(y ~ factor, data = ) | side-by-side boxplots, one per level | One-Way ANOVA |
plot(model) | the four diagnostic plots of a fitted model | One-Way ANOVA |
boxplot(x) | a boxplot of one variable | — |
barplot(table(x)) | a bar chart of category counts | — |
lines(), abline(), legend(), title() | add to an existing plot | Power curves |
ggplot2main— the titlexlab,ylab— axis labelspch— point shape (16 is a solid dot)cex— point and text size scale (0.4 is small)col— color, by name or fromrainbow(n)lwd,lty— line width and type (2 is dashed)
The ggplot2 package installed on the Packages tab builds graphics layer by layer and is the standard for publication-quality figures. A scatterplot with it looks like:
library(ggplot2)
ggplot(cars, aes(x = mpg, y = engine)) +
geom_point() +
labs(x = "Miles Per Gallon", y = "Engine Displacement")aes() maps columns to axes, geom_point() adds the points, labs() the labels; swap geom_point() for geom_boxplot() or geom_histogram() for the other plots on this sheet.
Where to go next
- R-intro.pdf — the official An Introduction to R, at cran.r-project.org/doc/manuals/r-release/
- rseek.org — an R-specific search engine
- www.stat.purdue.edu/scs — the Cars.csv data set and the original tutorial this sheet follows
- Cohen (1988) — Statistical Power Analysis for the Behavioral Sciences, for effect sizes and the 0.8 power convention
Every test on this sheet has a matching tab on the Statistics Formula Sheet: the t-tests and the F-test for variances under Tests for Means, chisq.test() under Chi-Squared Tests, aov() and the post-hoc tests under ANOVA, cor.test() and lm() under Regression, and the whole decision tree under Choosing the Right Test.