R REVISION LECTURE
Complete Line-by-Line Explanation
dplyr | ggplot2 | Logistic Regression | mtcars Dataset
WHAT THIS FILE COVERS
SECTION TOPICS
dplyr filter(), select(), mutate(), arrange(), pipe operator %>%
ggplot2 geom_point(), geom_smooth(), geom_histogram(), geom_density(),
geom_boxplot(), aes(), labs()
Combining Piping dplyr into ggplot2, chaining multiple transformations
Regression glm() for logistic regression, lm() for linear regression, summary()
Questions 1–7 Exam-style practice with full answer code
SECTION 1: SETUP — Installing & Loading Packages
The very first thing you always do before any analysis in R is install the packages you need, then load them into
the current session.
[Link]("dplyr")
library(dplyr)
data(mtcars)
mtcars
head(mtcars)
CODE WHAT IT DOES & WHY
[Link]("dplyr") Downloads and installs the dplyr package from CRAN (the
internet). You only need to run this ONCE ever on a computer
— not every time you open R. Comment it out after first use.
library(dplyr) Loads dplyr into your current R session so you can use its
functions like filter(), select() etc. You must run this every time
you open R.
data(mtcars) Loads the built-in mtcars dataset into your environment.
mtcars = Motor Trend Car Road Tests, 32 cars, 11 variables
like mpg (miles per gallon), hp (horsepower), cyl (cylinders).
mtcars Prints the entire dataset in the console. Not ideal for large
datasets — just shows all 32 rows.
head(mtcars) Shows only the FIRST 6 rows. Useful for a quick peek at
structure without flooding your console. head(mtcars, 10)
would show first 10 rows.
KEY RULE [Link]() = one-time download. library() = every session loader. Never skip
library() or your functions won't work.
SECTION 2: filter() — Keeping Only Rows You Want
filter() is like WHERE in SQL. It keeps only the rows that meet your condition, discarding all others. The first
argument is always the dataset.
filter(mtcars, mpg > 20)
CODE WHAT IT DOES & WHY
filter( The dplyr function for row filtering. Opens the function call.
mtcars, The dataset you want to filter. Always the first argument.
mpg > 20) The condition: keep only rows where mpg (miles per gallon) is
greater than 20. You can use >, <, >=, <=, ==, != as operators.
EXAM TIP == means 'is equal to' (comparison). A single = is assignment. filter(mtcars, cyl == 6) finds
6-cylinder cars. filter(mtcars, cyl = 6) is an ERROR.
Multiple conditions — use comma (AND) or & operator:
filter(mtcars, cyl == 6, mpg > 20) # AND: both must be true
filter(mtcars, cyl == 6 & mpg > 20) # same as above
filter(mtcars, cyl == 6 | mpg > 20) # OR: at least one must be true
SECTION 3: select() — Choosing Columns to Display
select() picks specific columns from a dataset. Use it to reduce clutter and show only what you need.
select(mtcars, mpg, hp)
CODE WHAT IT DOES & WHY
select( The dplyr function for column selection.
mtcars, The dataset — always first argument.
mpg, hp) The column names to KEEP. Every other column is dropped
from the output. You can list as many as you want, separated
by commas.
NOTE select() does NOT modify the original dataset unless you save it with <-. It just displays the
selected columns. Use: result <- select(mtcars, mpg, hp) to save it.
SECTION 4: mutate() — Creating New Variables (Columns)
mutate() adds one or more new columns to your dataset, usually calculated from existing columns. The original
dataset is not changed unless you save the result.
mutate(mtcars, efficiency = mpg / hp)
mutate(mtcars, mpg2 = mpg)
mtcars2 <- mutate(mtcars, efficiency = mpg / hp)
mtcars2
CODE WHAT IT DOES & WHY
mutate(mtcars, Apply mutate to the mtcars dataset.
efficiency = mpg / hp) Create a NEW column called 'efficiency', calculated as mpg
divided by hp for every row. The = sign here is ASSIGNMENT
inside mutate, not comparison.
mutate(mtcars, mpg2 = mpg) Creates a copy of the mpg column named mpg2.
Demonstrates you can name the new column anything.
mtcars2 <- mutate(...) Saves the result into a new object called mtcars2. Without
this, the new column is printed but NOT stored anywhere.
mtcars2 Prints the saved dataset with the new column so you can
verify it worked.
EXAM TIP In an exam if asked to 'create a new variable', always use mutate(). Remember:
new_name = formula. The formula can use any math: +, -, *, /, and even functions like
log(), sqrt().
SECTION 5: arrange() — Sorting Rows
arrange() sorts rows of the dataset by one or more columns. Default is ascending (smallest first). Wrap with desc()
for descending order.
arrange(mtcars, mpg) # ascending: lowest mpg first
arrange(mtcars, desc(mpg)) # descending: highest mpg first
CODE WHAT IT DOES & WHY
arrange(mtcars, mpg) Sort rows from lowest to highest mpg (ascending). Think A-Z
or 1-100.
arrange(mtcars, desc(mpg)) desc() reverses the order. Now highest mpg appears first.
Think Z-A or 100-1.
arrange(mtcars, cyl, mpg) Sort by cyl first, then by mpg within each cylinder group (multi-
column sort).
SECTION 6: The Pipe Operator %>% — Chaining Functions
The pipe operator %>% passes the result of one function directly into the next function as its first argument. It
makes code readable like a sentence: 'take data, THEN do this, THEN do that'.
READ IT AS mtcars %>% filter(mpg > 20) %>% select(mpg) = 'Take mtcars, THEN keep rows where
mpg > 20, THEN show only the mpg column'.
mtcars %>%
filter(mpg > 20) %>%
select(mpg)
mtcars %>%
filter(mpg > 20) %>%
select(mpg, hp)
mtcars %>%
filter(mpg > 20) %>%
mutate(eff = mpg / hp) %>%
select(mpg, hp, eff)
CODE WHAT IT DOES & WHY
mtcars %>% Start with the mtcars dataset and send it to the next function.
filter(mpg > 20) %>% Keep rows where mpg > 20. NOTE: when using pipes, you do
NOT repeat the dataset name inside the function — the pipe
sends it automatically.
select(mpg) From the filtered result, show only the mpg column.
mutate(eff = mpg / hp) %>% After filtering, create new column 'eff'. Then pipe that result to
select().
select(mpg, hp, eff) Finally, show only mpg, hp, and the new eff column.
CRITICAL filter() must come BEFORE select() if you filter on a column you later drop. mutate() must
ORDER come BEFORE select() if you want to display the new column. ORDER MATTERS —
wrong order = error.
SECTION 7: dplyr Examples — Full Walkthrough
Example 1: Cars with mpg > 25, sorted by mileage per cylinder
mtcars %>%
filter(mtcars, mpg > 25) %>%
mutate(mpc = mpg / cyl) %>%
select(mpg, cyl, mpc) %>%
arrange(desc(mpg))
CODE WHAT IT DOES & WHY
filter(mtcars, mpg > 25) Keep only cars where mpg exceeds 25. NOTE: When using
pipes, passing 'mtcars' again here is technically redundant
(the pipe already sends it), but it still works. In clean code
you'd write just filter(mpg > 25).
mutate(mpc = mpg / cyl) Create new column 'mpc' (mileage per cylinder) = mpg divided
by number of cylinders.
select(mpg, cyl, mpc) Show only three columns: mpg, cyl, and the new mpc.
arrange(desc(mpg)) Sort in descending order of mpg — best fuel economy at the
top.
BROKEN Lines 70-74 in the file show a BROKEN pipe chain — there is no %>% after
CODE arrange(desc(mpg)), so mutate() and select() are orphaned. This is a deliberate example of
WARNING what NOT to do. The code would error or behave unexpectedly.
Example 2: Cars with hp > 100, sorted by hp per cylinder ascending
mtcars %>%
filter(hp > 100) %>%
mutate(hppercyl = hp / cyl) %>%
select(hp, cyl, hppercyl) %>%
arrange(hppercyl)
CODE WHAT IT DOES & WHY
filter(hp > 100) Keep only high-power cars (more than 100 horsepower).
mutate(hppercyl = hp / cyl) Create 'hppercyl' = horsepower per cylinder. Tells you how
powerful each cylinder is on average.
select(hp, cyl, hppercyl) Display only these three columns.
arrange(hppercyl) Sort ASCENDING by hppercyl (no desc() = smallest first).
Cars with least hp per cylinder appear first.
SECTION 8: ggplot2 — Building Graphs Layer by Layer
ggplot2 builds plots in layers. You always start with ggplot() to define the dataset and aesthetics (axes, colours),
then ADD geometric layers with + and geom_*() functions.
STRUCTUR ggplot(data, aes(x=, y=)) + geom_something() + more_layers() The + connects layers —
E think of it like building a cake, one layer at a time.
8a: Scatterplot — geom_point()
ggplot(mtcars, aes(x = hp, y = mpg)) + geom_point()
CODE WHAT IT DOES & WHY
ggplot(mtcars, Tell ggplot2 which dataset to use. mtcars is the data source
for all layers.
aes(x = hp, y = mpg)) aes() = aesthetics mapping. x-axis = hp (horsepower), y-axis =
mpg (fuel economy). aes() maps data columns to visual
properties.
+ geom_point() Add a layer of points (dots) at each (hp, mpg) coordinate. This
makes it a scatterplot.
8b: Adding Colour by a Category
ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) + geom_point()
CODE WHAT IT DOES & WHY
color = factor(cyl) Colour each dot according to the cyl (cylinder) value. factor()
tells R to treat cyl as a CATEGORY (4, 6, 8 cylinders) not a
number. Without factor(), R would use a continuous colour
gradient instead of distinct colours.
8c: Adding a Trend Line (Regression Line) — geom_smooth()
# THREE separate trend lines (one per cylinder group):
ggplot(mtcars, aes(x = hp, y = mpg, color = factor(cyl))) +
geom_point() +
geom_smooth(method = 'lm')
# ONE overall trend line (colour only affects points):
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point(aes(color = factor(cyl))) +
geom_smooth(method = 'lm')
CODE WHAT IT DOES & WHY
geom_smooth(method = 'lm') Adds a trend line. method='lm' means Linear Model — a
straight regression line through the data. The grey shading
around it is the 95% confidence interval.
color in ggplot() main aes() When color is in the MAIN aes(), ALL layers (points AND
smooth) are split by that colour. You get 3 separate trend lines
for 3 cylinder groups.
color inside geom_point(aes(...)) When color is ONLY inside geom_point()'s aes(), only the
points are coloured by group. geom_smooth() doesn't see the
grouping, so it draws ONE overall line.
EXAM TIP In your exam, always write an interpretation: 'There is a negative non-linear relationship
between hp and mpg — as horsepower increases, fuel efficiency decreases. 4-cylinder
cars (red) have high mpg but low hp.'
SECTION 9: More Plot Types — histogram, density, boxplot
9a: Histogram — geom_histogram()
ggplot(mtcars, aes(x = mpg)) +
geom_histogram(binwidth = 2)
CODE WHAT IT DOES & WHY
aes(x = mpg) Histogram only needs an x-axis (it counts frequencies
automatically). No y = needed.
geom_histogram() Draws bars showing how many observations fall in each range
(bin).
binwidth = 2 Each bar covers a range of 2 mpg units. Smaller binwidth =
more narrow bars, more detail. Larger = fewer, wider bars.
Note: the file has a typo 'bindwidth' — correct spelling is
'binwidth'.
9b: Density Plot — geom_density()
ggplot(mtcars, aes(x = mpg)) +
geom_density()
# By category with fill:
ggplot(mtcars, aes(x = mpg, color = factor(cyl), fill = factor(cyl))) +
geom_density(alpha = 0.4)
CODE WHAT IT DOES & WHY
geom_density() Draws a smooth curve showing the probability distribution of
mpg. Like a smoothed histogram.
color = factor(cyl) Draws the curve OUTLINE in different colours for each
cylinder group.
fill = factor(cyl) Fills the AREA under each curve with the corresponding
colour.
alpha = 0.4 Sets transparency (0 = invisible, 1 = solid). 0.4 means 60%
transparent so overlapping areas are visible. Essential when
curves overlap.
9c: Boxplot — geom_boxplot()
# Horizontal boxplot:
ggplot(mtcars, aes(x = hp, y = "")) +
geom_boxplot()
# Vertical boxplot (preferred):
ggplot(mtcars, aes(x = "", y = hp)) +
geom_boxplot()
CODE WHAT IT DOES & WHY
aes(x = "", y = hp) The empty string x="" creates a single group (one box). Put
the variable you want to analyse on the y-axis for a vertical
boxplot.
geom_boxplot() Draws box-and-whisker plot. Box = IQR (middle 50% of data).
Line in box = median. Whiskers = 1.5 × IQR range. Dots
beyond whiskers = OUTLIERS.
aes(x = hp, y = "") Rotated version — variable on x-axis gives a horizontal
boxplot. Both are valid; vertical is more common.
EXAM Reading a boxplot: If the median line is not centred in the box, data is skewed. Dots
INTERPRET outside whiskers are potential outliers. A long upper whisker = right skew (some very high
ATION values).
SECTION 10: labs() — Adding Titles and Axis Labels
ggplot(mtcars, aes(x = mpg, color = factor(cyl), fill = factor(cyl))) +
geom_density(alpha = 0.4) +
labs(title = "Density of mpg by Cylinder Type",
x = "Miles Per Gallon")
CODE WHAT IT DOES & WHY
+ labs( Add a labels layer. Always use + to add it, never %>%.
title = "..." Sets the main title that appears at the top of the plot.
x = "..." Labels the x-axis. You can also add y = "..." for the y-axis
label.
SECTION 11: Question 1 — dplyr Multi-Step Pipeline
Task: Filter 6-cylinder cars where mpg > average mpg. Create power_ratio = hp/wt. Show mpg, hp, wt,
power_ratio. Sort descending by power_ratio.
library(dplyr)
mtcars %>%
filter(cyl == 6, mpg > mean(mpg, [Link] = TRUE)) %>%
mutate(power_ratio = hp / wt) %>%
select(mpg, hp, wt, power_ratio) %>%
arrange(desc(power_ratio))
CODE WHAT IT DOES & WHY
cyl == 6 == is the equality check (not assignment). Keeps only 6-
cylinder cars.
mpg > mean(mpg, [Link] = TRUE) mean(mpg) calculates the AVERAGE mpg of the entire
dataset (about 20.09). [Link]=TRUE means 'remove NAs
before calculating' — prevents errors if any values are
missing. So this keeps only 6-cyl cars that also have above-
average mpg.
filter(cond1, cond2) Comma between conditions means AND — both must be true
simultaneously.
mutate(power_ratio = hp / wt) Create new column: hp divided by wt (weight in 1000 lbs).
Higher value = more power relative to weight.
select(mpg, hp, wt, power_ratio) Keep only these four columns in the output.
arrange(desc(power_ratio)) Sort so highest power_ratio car appears first.
Alternative using & operator (identical result):
filter(cyl == 6 & mpg > mean(mpg, [Link] = TRUE))
Comma and & between filter conditions do the same thing — both mean AND. Use whichever you prefer.
SECTION 12: Question 2 — Scatter + Boxplot Analysis
Task: Plot relationship between wt and mpg with trend line. Check for outliers in mpg. Interpret.
library(ggplot2)
# Plot 1: Relationship wt vs mpg with trend line
ggplot(mtcars, aes(x = wt, y = mpg)) +
geom_point() +
geom_smooth(method = "lm")
# Plot 2: Boxplot to check outliers in mpg
ggplot(mtcars, aes(x = "", y = mpg)) +
geom_boxplot()
CODE WHAT IT DOES & WHY
aes(x = wt, y = mpg) wt is the predictor (x-axis), mpg is the outcome (y-axis). We
want to see how weight AFFECTS fuel economy.
geom_point() Plots each car as a dot at its (wt, mpg) position.
geom_smooth(method = "lm") Draws ONE overall regression line. Shaded area = 95%
confidence interval. Steep downward slope = strong negative
relationship.
aes(x = "", y = mpg) Boxplot for mpg distribution. Empty x="" = one single box for
all cars. Points outside whiskers = potential outliers.
EXPECTED Scatter: Strong negative relationship — heavier cars have worse fuel economy. This
INTERPRET makes physical sense (more mass = more fuel needed). Boxplot: Distribution is right-
ATION skewed (median below centre), a few cars have unusually high mpg (outliers at top).
SECTION 13: Question 3 — Histogram of hp
Task: Create histogram of hp. Check whether distribution appears normal.
ggplot(mtcars, aes(x = hp)) +
geom_histogram(binwidth = 20)
CODE WHAT IT DOES & WHY
aes(x = hp) hp goes on the x-axis. R automatically counts how many cars
fall in each hp range for the y-axis.
geom_histogram(binwidth = 20) binwidth = 20 means each bar covers 20 hp units (e.g., 50-70,
70-90, etc.). Choose binwidth based on the range of your data
— too small = noisy, too large = hides patterns.
INTERPRET If the histogram is roughly bell-shaped and symmetric, distribution is approximately normal.
ATION If it has a long tail to the right (most cars clustered at low hp, few very powerful cars), it is
RIGHT-SKEWED — not normal. This matters for statistical tests.
SECTION 14: Question 4 — Density Plot by Cylinder
Task: Density plot of mpg, separate curves for each cylinder type, adjust transparency, add title and labels.
ggplot(mtcars, aes(x = mpg,
color = factor(cyl),
fill = factor(cyl))) +
geom_density(alpha = 0.4) +
labs(title = "Density of mpg by Cylinder Type",
x = "Miles Per Gallon")
CODE WHAT IT DOES & WHY
color = factor(cyl) Separate outline colour for each cylinder group (4, 6, 8).
factor() ensures R treats them as categories.
fill = factor(cyl) Fills the area under each density curve with matching colour.
geom_density(alpha = 0.4) Draws smooth distribution curves. alpha=0.4 makes fills 60%
transparent so overlapping areas (where distributions mix) are
still visible.
labs(title=..., x=...) Adds informative title and x-axis label. Good practice and
often required in exams for full marks.
INTERPRET 4-cylinder cars (one peak): peak at high mpg (~30). 8-cylinder cars: peak at low mpg (~15).
ATION 6-cylinder cars: in between. Confirms: more cylinders = more power but worse fuel
economy.
SECTION 15: Question 5 — Missing Values & Outlier Detection
Task: Check for missing values in hp. Calculate mean ignoring NAs. Identify outliers visually.
library(dplyr)
# NOTE: line 227 has a typo: library(ggplot) should be library(ggplot2)
library(ggplot2)
[Link](mtcars$hp) # check for missing values
mean(mtcars$hp, [Link] = TRUE) # mean ignoring NAs
ggplot(mtcars, aes(x = "", y = hp)) + # outlier visualisation
geom_boxplot()
CODE WHAT IT DOES & WHY
[Link](mtcars$hp) [Link]() returns TRUE for each row where hp is missing (NA),
FALSE where it has a value. mtcars$hp means 'the hp column
from mtcars' (dollar sign accesses a column). If all FALSE →
no missing values.
mean(mtcars$hp, [Link] = TRUE) Calculates the average horsepower. [Link] = TRUE means
'remove NAs before calculating'. Without this, if ANY value is
NA, mean() returns NA instead of a number. In mtcars there
are no NAs, but it's always good practice.
geom_boxplot() for outliers Points plotted beyond the whiskers of the boxplot are
statistical outliers (more than 1.5 × IQR from Q1 or Q3). This
gives a visual, easy way to spot them without any calculations.
TYPO IN Line 227: library(ggplot) is WRONG — the package is called ggplot2, not ggplot. This
FILE would give an error 'there is no package called ggplot'. Always write library(ggplot2).
SECTION 16: Question 6 — Logistic & Linear Regression
Task: Predict transmission type (am: 0=automatic, 1=manual) using wt and hp. am is binary (0 or 1) so logistic
regression is appropriate. The file also shows linear regression for comparison.
# LOGISTIC REGRESSION (correct approach for binary outcome):
model <- glm(am ~ wt + hp, data = mtcars, family = "binomial")
summary(model)
# LINEAR REGRESSION (shown for comparison, not ideal for binary):
model_linear <- lm(am ~ wt + hp, data = mtcars)
summary(model_linear)
CODE WHAT IT DOES & WHY
glm() General Linear Model — handles various distribution families.
Used here for logistic regression.
am ~ wt + hp Formula notation. am is the outcome (left of ~). wt and hp are
predictors (right of ~). + adds multiple predictors.
data = mtcars The dataset containing all these variables.
family = "binomial" CRITICAL — this tells glm() to use logistic regression (suitable
for binary 0/1 outcomes like am). Without this, it would default
to ordinary linear regression.
summary(model) Prints full results: coefficients, standard errors, z-values, p-
values, AIC. Look for p-values < 0.05 for significant predictors.
lm(am ~ wt + hp, ...) Ordinary Linear Model. Technically not ideal for binary
outcomes (predictions can go below 0 or above 1), but shown
here for comparison. lm() does NOT need a family argument.
KEY Binary outcome (0/1, yes/no, true/false) = use glm(..., family='binomial') = LOGISTIC
DIFFERENC regression. Continuous outcome (price, weight, income) = use lm() = LINEAR regression.
E Using lm() on a binary variable is technically wrong but your professor shows both for
comparison.
Reading summary() output for glm():
OUTPUT ELEMENT WHAT IT MEANS
Coefficients The estimated log-odds change per unit increase in each predictor.
Pr(>|z|) p-value. If < 0.05, the predictor is statistically significant.
*** symbols Significance stars: *** = very significant, ** = significant, * = marginally
significant, . = borderline, nothing = not significant.
AIC Akaike Information Criterion — lower is better. Used to compare
competing models.
Null deviance How well a model with only an intercept fits the data.
Residual deviance How well YOUR model fits. Much lower than null deviance = model is
helpful.
SECTION 17: Question 7 — Piping dplyr into ggplot2
Task: Filter cars with mpg > 18, create efficiency = mpg/wt, plot wt vs efficiency with trend line.
This is an advanced technique — you can chain dplyr transformations and then pipe the result directly into
ggplot2 without saving an intermediate dataset.
mtcars %>%
filter(mpg > 18) %>%
mutate(efficiency = mpg / wt) %>%
ggplot(aes(x = wt, y = efficiency)) +
geom_point() +
geom_smooth(method = "lm")
CODE WHAT IT DOES & WHY
mtcars %>% filter(mpg > 18) %>% First pipe: take mtcars, keep only cars with mpg > 18. 14 cars
are removed.
mutate(efficiency = mpg / wt) %>% Second pipe: create efficiency column (mpg per 1000 lbs of
weight) for the filtered cars.
ggplot(aes(x = wt, y = efficiency)) CRITICAL: After the last pipe, ggplot() appears WITHOUT a
+
dataset argument. The pipe sends the transformed data
automatically. aes() defines axes. Note the switch from %>%
to + here — dplyr uses %>%, ggplot2 uses +.
geom_point() Plot each filtered car as a dot.
geom_smooth(method = "lm") Add a straight trend line through the filtered data.
SWITCH This is the most common mistake students make: dplyr functions are chained with %>%
FROM %>% (pipe). ggplot2 layers are connected with + (plus). When you transition from dplyr to
TO + ggplot2, switch from %>% to +. You can see this in line 259: ggplot(...) uses + for its layers.
EXPECTED As wt increases among efficient cars (mpg > 18), efficiency (mpg/wt) generally decreases
INTERPRET — heavier cars are less fuel efficient per unit of weight. The trend line quantifies this
ATION relationship.
SECTION 18: EXAM QUICK-REFERENCE CHEATSHEET
FUNCTION PURPOSE & SYNTAX
filter(data, condition) Keep rows matching condition. Operators: ==, !=, >, <, >=, <=. AND:
comma or &. OR: |
select(data, col1, col2) Keep only specified columns. Drop the rest.
mutate(data, new=formula) Create a new column using a formula on existing columns.
arrange(data, col) Sort ascending. arrange(data, desc(col)) for descending.
mean(x, [Link]=TRUE) Average of x, ignoring NA values. Always add [Link]=TRUE.
[Link](x) Returns TRUE for each missing value, FALSE for present. Sum it:
sum([Link](x)) counts total NAs.
ggplot(data, aes(x=,y=)) Start a ggplot. All following layers use + not %>%.
geom_point() Add scatter plot dots.
geom_smooth(method='lm') Add regression trend line. Shaded area = confidence interval.
geom_histogram(binwidth=n) Distribution bars. binwidth controls bar width.
geom_density(alpha=0.4) Smooth distribution curve. alpha controls transparency.
geom_boxplot() Box and whisker plot. Dots = outliers. Line = median.
factor(x) Convert numeric to categorical (e.g., cyl = 4,6,8 becomes 3 groups).
labs(title=,x=,y=) Add title and axis labels to a ggplot.
lm(y ~ x, data=d) Linear regression model. summary() shows results.
glm(y ~ x, data=d, Logistic regression for binary (0/1) outcome. summary() shows results.
family='binomial')
%>% Pipe: passes left result as first argument to right function. Used in dplyr
chains.
+ Layer connector in ggplot2. Adds geom_, labs(), theme() etc.
SECTION 19: Common Mistakes Found in This File
LINE WRONG CODE CORRECT VERSION & WHY
112 geom_histogram(bindwidth=2) geom_histogram(binwidth=2) — 'bind' not
'bind'. Typo causes error.
227 library(ggplot) library(ggplot2) — the package is ggplot2.
ggplot alone doesn't exist.
70-74 Broken pipe chain — no %>% after Every line except the last must end with %>%.
arrange() Without it, mutate() and select() become
orphaned statements.
57,64 filter(mtcars, mpg>25) inside a pipe filter(mpg>25) — when using %>%, the dataset
is already passed in. Repeating it is redundant
(though usually harmless).
Good luck in your exam!
Remember: filter → mutate → select → arrange | ggplot() + geom_*() + labs() | lm() for linear, glm(family='binomial') for
logistic