Use vectors, tables and statistical functions to explore data.

Before starting: Rows, columns, basic arithmetic, and an R installation.

Practice project: Produce a reproducible report with missing-data decisions documented.

1. Introduction, Foundations & R Environment

  1. R Introduction, History & The Statistical Computing Paradigm
  2. RStudio IDE, Console Mechanics & Workspace Management
    Read the example and try it

    Run the same script from the console and from a saved file. The version string identifies the runtime used for each run.

    R script or RStudio console. Install any package named with :: before using its functions.

    print(R.version.string)

    Print a long vector and compare prefixes on successive lines.

    Set options(width=30), then print 1:40.

    Expected result
    Several lines appear. Each bracketed prefix equals the one-based position of the first value on that line. The line breaks depend on the print width.
  3. Variables, Assignment Operators (<- vs =) & Dynamic Typing
    Read the example and try it

    An assignment changes the value associated with a name. Read the result after subtracting the two booked seats.

    R script or RStudio console. Install any package named with :: before using its functions.

    seats <- 8
    seats <- seats - 2
    print(seats)

    Assign a number and then text to one name and inspect each type.

    Assign 2 to x, then assign "Lab".

    Expected result
    double then character.
  4. Basic Atomic Data Types: Numeric, Integer, Character, Logical & Complex
    Read the example and try it

    The suffix L marks an integer literal. Compare the stored types of two values that print almost identically.

    R script or RStudio console. Install any package named with :: before using its functions.

    print(c(typeof(3), typeof(3L), typeof(TRUE)))

    Compare typeof for an integer literal and an ordinary numeric literal.

    Compare typeof(3L) with typeof(3).

    Expected result
    integer then double.
  5. Arithmetic, Relational & Logical Operators & Vector Recycling Rules
    Read the example and try it

    The shorter vector repeats across the longer one. Use lengths that divide evenly to make that repetition deliberate.

    R script or RStudio console. Install any package named with :: before using its functions.

    print(c(20, 40, 60, 80) + c(1, 2))

    Compare adding lengths four and two with lengths five and two.

    Add c(10,20) to 1:4 and then to 1:5.

    Expected result
    First: 11,22,13,24. Second: 11,22,13,24,15 with a fractional-recycling warning.

2. Core Data Structures — Vectors, Factors & Matrices

  1. Atomic Vectors: Creation, Sequence Generation & Automatic Coercion
    Read the example and try it

    All entries in an atomic vector share a type. Adding a character label converts the numeric entry to text.

    R script or RStudio console. Install any package named with :: before using its functions.

    labels <- c(4, "unknown")
    print(labels)
    print(typeof(labels))

    Combine an integer and a room name and inspect the result.

    Combine 3L and "Lab" using c.

    Expected result
    A character vector holding "3" and "Lab".
  2. Vector Indexing: Positive, Negative & Logical Subsetting
    Read the example and try it

    Use a logical mask to keep readings above a threshold. The surviving values stay in their original order.

    R script or RStudio console. Install any package named with :: before using its functions.

    rain <- c(1, 8, 4, 9)
    print(rain[rain > 4])

    Select the first, last and all but the second entries.

    Use x=c(4,8,6).

    Expected result
    First 4, last 6, all except position two: 4,6.
  3. Factors & Categorical Variables: Levels, Ordering & Contrasts
    Read the example and try it

    Set the order of category levels to match the real-world sequence. The sorting rule now understands size order.

    R script or RStudio console. Install any package named with :: before using its functions.

    sizes <- factor(c("L","S","M"), levels=c("S","M","L"), ordered=TRUE)
    print(sort(sizes))

    Reorder category levels and inspect the displayed order.

    Use factor(c("high","low"),levels=c("low","high")).

    Expected result
    Values still read high, low. Levels are ordered low, high.
  4. Matrices: 2D Grids, Dimensionality & Labeled Indexing
    Read the example and try it

    By default a matrix fills down each column first. Setting byrow changes where the second input goes.

    R script or RStudio console. Install any package named with :: before using its functions.

    print(matrix(1:6, nrow=2))
    print(matrix(1:6, nrow=2, byrow=TRUE))

    Construct a 2-by-3 matrix with and without byrow=TRUE.

    Use 1:6 in two rows.

    Expected result
    Default rows: [1,3,5], [2,4,6]. With byrow=TRUE: [1,2,3], [4,5,6].
  5. Matrix Operations & Linear Algebra (%*%, t, solve, det)
    Read the example and try it

    A row of quantities multiplied by a column of prices gives one total. The inner dimensions must agree.

    R script or RStudio console. Install any package named with :: before using its functions.

    qty <- matrix(c(2,3), nrow=1)
    price <- matrix(c(4,5), ncol=1)
    print(qty %*% price)

    Compare elementwise multiplication with a matrix product.

    Set A to [[1,2],[3,4]] in row order and multiply it by itself.

    Expected result
    A*A has rows [1,4] and [9,16]. A %*% A has rows [7,10] and [15,22].

3. Advanced Data Structures — Arrays, Lists & Data Frames

  1. Multidimensional Arrays: Higher-Order Tensors & Dimension Names
    Read the example and try it

    A third dimension can represent separate days. Pick day two while leaving the first two dimensions unrestricted.

    R script or RStudio console. Install any package named with :: before using its functions.

    readings <- array(1:12, dim=c(2,3,2))
    print(readings[,,2])

    Create a 2-by-3-by-4 array and select one slice.

    Use array(1:24,dim=c(2,3,4)) and inspect the first layer.

    Expected result
    First layer rows: [1,3,5], [2,4,6].
  2. Lists: Heterogeneous Data Collections & Tree Structures
    Read the example and try it

    A list can hold fields of different types. Double brackets or a name select the stored value itself.

    R script or RStudio console. Install any package named with :: before using its functions.

    trip <- list(route="B", minutes=c(4,7))
    print(sum(trip$minutes))

    Build a named list with three different kinds of entries.

    Use name="Lab", seats=8L and open=TRUE in a list.

    Expected result
    The entries retain types character, integer and logical.
  3. List Manipulation: Nesting, Recursive Modification & unlist()
    Read the example and try it

    A nested list keeps a passenger and ticket together. Modify the field at the right depth.

    R script or RStudio console. Install any package named with :: before using its functions.

    booking <- list(ticket=list(seat=3L))
    booking$ticket$seat <- 4L
    print(booking$ticket)

    Compare the classes of x[1] and x[[1]].

    Use x=list(8L,"Lab").

    Expected result
    class(x[1]) is list. class(x[[1]]) is integer.
  4. Data Frames: Tabular Architecture & Column-Oriented Storage
    Read the example and try it

    Columns in a data frame can have different types but share a row count. Each row here describes one route.

    R script or RStudio console. Install any package named with :: before using its functions.

    routes <- data.frame(name=c("Hill","Lake"), minutes=c(8,5))
    print(routes)

    Create a data frame with a label and a numeric measurement.

    Build one row with room="Lab" and visits=8L.

    Expected result
    One row, two columns; room is character and visits is integer.
  5. Data Frame Wrangling: Filtering, Slicing, New Columns & order()
    Read the example and try it

    Order returns positions. Apply them to the whole table so room names follow their capacities.

    R script or RStudio console. Install any package named with :: before using its functions.

    rooms <- data.frame(name=c("Lab","Hall"), seats=c(9,4))
    print(rooms[order(rooms$seats), ])

    Use the order of scores to reorder complete data-frame rows.

    Use Lab=8, Hall=2 and Gym=5. Sort ascending.

    Expected result
    Rows are Hall=2, Gym=5, Lab=8.

4. Control Flow, Loops & Conditionals

  1. Conditional Branching: if, else if, else & Vectorized ifelse()
    Read the example and try it

    Use ifelse when each ticket needs its own label. One comparison produces one decision per ticket.

    R script or RStudio console. Install any package named with :: before using its functions.

    print(ifelse(c(0,2,1) > 0, "open", "full"))

    Compare a single branch decision with vectorized ifelse.

    Use scores c(3,7), pass threshold 5.

    Expected result
    A scalar if on the first value selects retry. Vectorized ifelse returns retry, pass.
  2. Multi-Branch Switching: The switch() Function
    Read the example and try it

    A named switch selects the branch matching a text value. Give the final unnamed choice as a fallback.

    R script or RStudio console. Install any package named with :: before using its functions.

    mode <- "bus"
    print(switch(mode, rail=8, bus=4, 0))

    Map two route names to actions and handle an unknown name.

    Map lab→open, hall→wait, other names→unknown.

    Expected result
    lab, hall, gym produce open, wait, unknown.
  3. For Loops: Iteration Mechanics, seq_along() & Preallocation
    Read the example and try it

    Allocate room for the answers before looping. seq_along handles empty inputs without creating an invalid first index.

    R script or RStudio console. Install any package named with :: before using its functions.

    fares <- c(3,5)
    bills <- numeric(length(fares))
    for (i in seq_along(fares)) bills[i] <- 2 * fares[i]
    print(bills)

    Trace both index expressions for an empty vector.

    Use an empty integer vector.

    Expected result
    seq_along returns integer(0). 1:length(x) returns c(1,0), which would incorrectly enter the loop twice.
  4. While Loops, Repeat Constructs & Loop Control (break, next)
    Read the example and try it

    A loop needs a change that brings it closer to stopping. Count down until all remaining seats have been taken.

    R script or RStudio console. Install any package named with :: before using its functions.

    left <- 3
    while (left > 0) { print(left); left <- left - 1 }

    Add a limit to a repeat loop before running it.

    Start n at zero, increment each pass and stop at n=3.

    Expected result
    3
  5. Vectorization vs Explicit Loops: SIMD Performance in R
    Read the example and try it

    An operation on a vector updates every entry in one expression. Compare the resulting length with the number of input readings.

    R script or RStudio console. Install any package named with :: before using its functions.

    minutes <- c(2,3,5)
    print(minutes * 60)

    Compare preallocated looping with a vector operation.

    Double c(2,4,6) by indexed writes and by vector multiplication.

    Expected result
    Both give 4,8,12; their values compare equal.

5. Functions, Scope & Functional Programming

  1. User-Defined Functions: Syntax, Default Arguments & Return Values
    Read the example and try it

    A default argument handles a regular fare. The caller can supply another fare for a special event.

    R script or RStudio console. Install any package named with :: before using its functions.

    bill <- function(qty, fare=4) qty * fare
    print(c(bill(2), bill(2, fare=6)))

    Write a mean-adjustment function and inspect its result.

    Subtract the mean from c(2,4,6).

    Expected result
    −2, 0, 2. The adjusted values average zero.
  2. Lexical Scoping, Environments & The Super-Assignment Operator (<<-)
    Read the example and try it

    A returned function can remember the environment where it was created. Each counter factory call creates a separate count.

    R script or RStudio console. Install any package named with :: before using its functions.

    new_counter <- function() { n <- 0; function() { n <<- n + 1; n } }
    next_id <- new_counter()
    print(c(next_id(), next_id()))

    Build a closure retaining its own starting value.

    Make an adder retaining 5 and call it with 3.

    Expected result
    8
  3. The Ellipsis (...): Variable Arguments & Argument Passthrough
    Read the example and try it

    Forward optional arguments to the function doing the calculation. Here na.rm decides how missing readings affect the mean.

    R script or RStudio console. Install any package named with :: before using its functions.

    average <- function(x, ...) mean(x, ...)
    print(average(c(4,NA,8), na.rm=TRUE))

    Forward na.rm to a summary function.

    Compute the mean of 2, NA, 6 with na.rm=TRUE forwarded through ... .

    Expected result
    4
  4. The Apply Family: Matrix apply(), List lapply() & sapply()
    Read the example and try it

    The margin tells apply which dimension to keep. Margin one gives one total for each row.

    R script or RStudio console. Install any package named with :: before using its functions.

    grid <- matrix(1:6, nrow=2)
    print(apply(grid, 1, sum))

    Compare outputs when each callback returns a different length.

    Apply seq_len to the integers 1 and 3 with lapply and sapply.

    Expected result
    The results cannot simplify to a rectangular numeric array. Both contain a length-one vector and a length-three vector.
  5. Robust Functional Mapping: vapply(), tapply() & Multivariate mapply()
    Read the example and try it

    Give vapply an expected type and length. An empty group should contribute the integer zero.

    R script or RStudio console. Install any package named with :: before using its functions.

    groups <- list(a=c(4,7), b=integer())
    print(vapply(groups, length, integer(1)))

    Require one numeric result per list entry.

    Use a list of c(2,4) and c(3,7); require one double per mean.

    Expected result
    3 and 5. Returning length two would violate numeric(1).

6. Data Cleaning, Missing Data & Strings

  1. Missing Data Semantics: NA, NULL, NaN, Inf & Cleaning Strategies
    Read the example and try it

    A missing count and a count of zero carry different information. Check missingness before calculating an average.

    R script or RStudio console. Install any package named with :: before using its functions.

    counts <- c(0,NA,6)
    print(is.na(counts))
    print(mean(counts, na.rm=TRUE))

    Distinguish a missing observation, NULL and NaN.

    Test is.na(NA), length(NULL), is.nan(NaN) and is.na(NaN).

    Expected result
    TRUE, 0, TRUE, TRUE respectively.
  2. Base String Manipulation: paste(), sprintf(), substr() & strsplit()
    Read the example and try it

    Padding a number changes its display, while the underlying count can remain numeric.

    R script or RStudio console. Install any package named with :: before using its functions.

    print(sprintf("Gate %02d", c(3,12)))

    Build room labels with paste and paste0 and compare.

    Join Room and 2.

    Expected result
    paste gives "Room 2"; paste0 gives "Room2".
  3. Regular Expressions in Base R: grep(), grepl(), sub() & gsub()
    Read the example and try it

    Anchor a pattern to match a prefix only at the start. A prefix appearing later in a label will fail.

    R script or RStudio console. Install any package named with :: before using its functions.

    print(grepl("^BUS-", c("BUS-4","OLD-BUS-4")))

    Match labels beginning with LAB rather than labels containing LAB anywhere.

    Test LAB1, XLAB and LAB2 against ^LAB.

    Expected result
    TRUE, FALSE, TRUE.
  4. Modern Text Processing with stringr: Consistent Vectorized String APIs
    Read the example and try it

    Extract the numeric part of a label with stringr. The extracted result is text until converted.

    R script or RStudio console. Install any package named with :: before using its functions.

    print(as.integer(stringr::str_extract("Desk 014", "[0-9]+")))

    Build a mask for room names containing a digit.

    Use room names Lab2, Hall and R7.

    Expected result
    TRUE, FALSE, TRUE. With stringr, use str_detect(names,"[0-9]"); base R gives the same mask.
  5. Date & Time Handling: as.Date(), POSIXct / POSIXlt & lubridate
    Read the example and try it

    Date subtraction measures the interval between dates. Set a timezone explicitly for timestamps used across locations.

    R script or RStudio console. Install any package named with :: before using its functions.

    start <- as.Date("2025-06-12")
    print(as.Date("2025-06-15") - start)

    Compare two timestamps with identical clocks and different zones.

    Parse 12:00 on January 15, 2025 in UTC and America/New_York.

    Expected result
    New York noon is 17:00 UTC that day, five hours later than UTC noon.

7. The Tidyverse Ecosystem — dplyr & tidyr

  1. The Tidyverse Philosophy & Pipe Operators: Native |> vs Magrittr %>%
    Read the example and try it

    Follow the pipe from left to right. The previous result becomes the first argument of the next function.

    R script or RStudio console. Install any package named with :: before using its functions.

    print(c(2,4,9) |> sort(decreasing=TRUE) |> head(2))

    Rewrite a two-step transformation with and without a pipe.

    Take abs of c(-2,3) and then sum, with and without a pipe.

    Expected result
    Both return 5.
  2. Data Wrangling with dplyr: filter(), select() & arrange()
    Read the example and try it

    Filter rows before selecting the columns needed for display. Arranging the result determines display order.

    R script or RStudio console. Install any package named with :: before using its functions.

    d <- data.frame(room=c("C","A","B"), seats=c(7,9,2))
    print(d |> dplyr::filter(seats >= 5) |> dplyr::arrange(room))

    Keep open rooms, choose two columns and order by capacity.

    Rows: Lab/open/8, Gym/closed/9, Hall/open/5. Return name and seats ascending by seats.

    Expected result
    Hall=5 then Lab=8, with no Gym row.
  3. Feature Engineering with dplyr: mutate(), transmute() & rename()
    Read the example and try it

    A derived column keeps the original inputs available for checking. Multiply quantity by price per unit.

    R script or RStudio console. Install any package named with :: before using its functions.

    items <- data.frame(qty=c(2,4), fare=c(5,3))
    print(dplyr::mutate(items, total=qty*fare))

    Add a per-seat measure and rename it.

    Use visits=12 and seats=4. Name the new visits-per-seat column rate.

    Expected result
    rate=3; original visits and seats remain when using mutate.
  4. Grouped Aggregations with dplyr: group_by(), summarize() & count()
    Read the example and try it

    Rows with the same route contribute to one group total. Name the result so its unit remains clear.

    R script or RStudio console. Install any package named with :: before using its functions.

    d <- data.frame(route=c("A","B","A"), kg=c(2,4,5))
    print(d |> dplyr::group_by(route) |> dplyr::summarise(total_kg=sum(kg)))

    Find each room's mean and its number of observed values.

    Use Lab visits c(2,NA,4) and Hall visits c(5,7).

    Expected result
    Lab: mean 3 from 2 observations. Hall: mean 6 from 2 observations.
  5. Reshaping Tidy Data with tidyr: pivot_longer(), pivot_wider() & separate()
    Read the example and try it

    Move weekdays out of column names and into a day field. This allows the same calculation across any number of days.

    R script or RStudio console. Install any package named with :: before using its functions.

    d <- data.frame(room="A", Mon=4, Tue=7)
    print(tidyr::pivot_longer(d, Mon:Tue, names_to="day", values_to="visits"))

    Convert Monday and Tuesday columns to day and value columns.

    Use one Lab row with Monday=2 and Tuesday=4.

    Expected result
    Two rows: Lab, Monday, 2 and Lab, Tuesday, 4. room remains the identifier.

8. Data Import, Export & Database Connectivity

  1. Flat File I/O: Base read.csv(), readr::read_csv() & data.table::fread()
    Read the example and try it

    Specify the ID type during import so leading zeros survive. Read a tiny CSV string before testing a larger file.

    R script or RStudio console. Install any package named with :: before using its functions.

    d <- read.csv(text="id,seats\n007,4", colClasses=c("character","integer"))
    print(d$id)

    Import an identifier with a leading zero as text.

    Read CSV text id,room followed by 007,Lab and require character IDs.

    Expected result
    The ID prints as "007", including both leading zeros.
  2. Excel Spreadsheets: Importing & Exporting with readxl and writexl
    Read the example and try it

    Write a named sheet and read it back by name. This example needs the writexl and readxl packages.

    R script or RStudio console. Install any package named with :: before using its functions.

    path <- tempfile(fileext=".xlsx")
    writexl::write_xlsx(list(Rooms=data.frame(seats=4)), path)
    print(readxl::read_excel(path, sheet="Rooms")$seats)

    Read a worksheet that has a title above its headers.

    A sheet begins with a title, then headers Room and Visits, then Lab and 8.

    Expected result
    Skip one title row when reading. The table has column names Room and Visits and its first record is Lab,8. The title is not a data column.
  3. Native R Serialization: Single Objects (saveRDS, readRDS) & Workspaces
    Read the example and try it

    Serialise one object and restore it into a name chosen by the reader. Check that the round trip retained its values.

    R script or RStudio console. Install any package named with :: before using its functions.

    path <- tempfile()
    saveRDS(c(3L,8L), path)
    print(identical(readRDS(path), c(3L,8L)))

    Save a data frame and restore it under a different name.

    Save data.frame(room="Lab",n=2L) to a temporary RDS file and read it as restored.

    Expected result
    identical(original,restored) is TRUE.
  4. Web APIs & JSON Data: HTTP Requests with httr2 & Parsing with jsonlite
    Read the example and try it

    Parse a small response body before connecting a live API. Check the field you need before using its value.

    R script or RStudio console. Install any package named with :: before using its functions.

    body <- '{"room":"Lab","seats":7}'
    result <- jsonlite::fromJSON(body)
    print(result$seats)

    Handle an error response separately from a valid JSON payload.

    Simulate HTTP 200 with {"visits":8} and HTTP 404 with {"error":"missing"}.

    Expected result
    HTTP 200 returns the visits value 8. HTTP 404 records status 404 and skips visits. If you handle status codes yourself with httr2, set req_error(is_error = function(resp) FALSE) before req_perform(); otherwise a 404 raises an error before your status check.
  5. Relational Databases & SQL in R: DBI, RSQLite & dbplyr
    Read the example and try it

    Bind a value through DBI instead of formatting it into SQL. This example runs against a temporary in-memory SQLite database.

    R script or RStudio console. Install any package named with :: before using its functions.

    con <- DBI::dbConnect(RSQLite::SQLite(), ":memory:")
    print(DBI::dbGetQuery(con, "SELECT ? AS seat", params=list(4)))
    DBI::dbDisconnect(con)

    Query a name with an apostrophe through DBI parameters.

    Create a SQLite table containing O'Brien and bind the name to a ? placeholder.

    Expected result
    Exactly one row returns with the original apostrophe. Supply params=list(name) to DBI::dbGetQuery.

9. Statistical Graphics, Base Plotting & ggplot2

  1. Base R Graphics: Scatter Plots, Line Charts & Multi-Panel Layouts
    Read the example and try it

    A scatter plot pairs two values from the same observation. Give each axis a unit so a reader can interpret its scale.

    R script or RStudio console. Install any package named with :: before using its functions.

    plot(c(1,3,5), c(4,7,8), xlab="Practice hours", ylab="Tasks solved")

    Plot study time against score and label both axes.

    Plot learner data (10,2), (20,5), (30,7).

    Expected result
    A scatterplot has three points, x-axis Study time (minutes) and y-axis Score. No line is required.
  2. Base Distribution Plots: hist(), boxplot(), barplot() & pie()
    Read the example and try it

    A bar plot can show one height for each route count. Count the observations first with table.

    R script or RStudio console. Install any package named with :: before using its functions.

    barplot(table(c("Hill","Lake","Hill")), ylab="Trips")

    Try two bin widths and compare visible peaks.

    Use [1,1,2,3,5,5] and left-closed bins with edges [0,3,6] then [0,2,4,6].

    Expected result
    Counts are [3,3] and [2,2,2]. Changing binning changes the apparent peaks.
  3. Introduction to ggplot2: The Grammar of Graphics Architecture
    Read the example and try it

    Map data fields to plot positions, then choose the mark that will represent a row.

    R script or RStudio console. Install any package named with :: before using its functions.

    trips <- data.frame(km=c(2,4,7), minutes=c(8,12,20))
    print(ggplot2::ggplot(trips, ggplot2::aes(km,minutes)) + ggplot2::geom_point())

    Map a group to color and set a constant point size separately.

    Plot two groups A and B in different colors, all points size 3.

    Expected result
    Group is mapped inside aes(color=group); size=3 is set outside aes in geom_point. The legend identifies groups, not point size.
  4. Core ggplot2 Geometries: geom_point, geom_line, geom_bar & geom_boxplot
    Read the example and try it

    Use geom_col when you already have counts. Each bar's height is the supplied total.

    R script or RStudio console. Install any package named with :: before using its functions.

    d <- data.frame(route=c("A","B"), trips=c(5,9))
    print(ggplot2::ggplot(d,ggplot2::aes(route,trips)) + ggplot2::geom_col())

    Compare plotting summary totals with counting raw observations.

    Use three raw records A,A,B and summary totals A=2, B=1.

    Expected result
    geom_bar on raw records and geom_col on the summary both yield heights 2 and 1. Counting the two summary rows would wrongly yield 1 and 1.
  5. ggplot2 Advanced Styling: Faceting (facet_wrap), Custom Scales & Themes
    Read the example and try it

    Split a plot into panels to compare routes without overlapping their labels. Shared scales preserve comparability.

    R script or RStudio console. Install any package named with :: before using its functions.

    d <- data.frame(route=c("A","A","B","B"),day=c(1,2,1,2),n=c(3,5,7,4))
    print(ggplot2::ggplot(d,ggplot2::aes(day,n)) + ggplot2::geom_line() + ggplot2::facet_wrap(~route))

    Compare fixed and free scales across two room panels.

    Plot room A values 1,2 and room B values 10,20 in separate panels.

    Expected result
    Fixed y scales show the larger values in B directly. Free y scales emphasize within-room variation; compare tick labels before comparing heights.

10. Statistical Analysis, Modeling & R Markdown / Reporting

  1. Descriptive Statistics & Bivariate Correlation: summary(), cor() & cov()
    Read the example and try it

    Correlation describes association. Inspect a scatter plot for outliers before interpreting a large value.

    R script or RStudio console. Install any package named with :: before using its functions.

    hours <- c(1,2,3,4)
    tasks <- c(2,5,5,8)
    print(cor(hours,tasks))

    Compare the observed mean with the mean after zero filling.

    Use c(2,NA,4).

    Expected result
    Observed mean is 3. Replacing missing with zero gives mean 2.
  2. Probability Distributions: Normal, Binomial, Poisson & Random Sampling
    Read the example and try it

    Set a seed to repeat a classroom simulation. Each result is a success count from five trials.

    R script or RStudio console. Install any package named with :: before using its functions.

    set.seed(12)
    print(rbinom(6, size=5, prob=.5))

    Simulate observations and distinguish draws from cumulative probabilities.

    Draw 5 values from N(0,1) and evaluate pnorm(0).

    Expected result
    Five simulated numbers, then 0.5. The latter is a cumulative probability, not another random draw.
  3. Statistical Hypothesis Testing: Student's t.test(), ANOVA (aov) & chisq.test()
    Read the example and try it

    Compare matched pupils using the differences within pairs. Keep the pupil order the same in both input vectors.

    R script or RStudio console. Install any package named with :: before using its functions.

    before <- c(4,8,5,7,9)
    after <- c(5,8,8,8,11)
    print(t.test(after, before, paired=TRUE)$estimate)

    Calculate one before-after difference per learner.

    Before=5,8,7; after=7,8,10 in the same learner order.

    Expected result
    2, 0, 3. Keep the pairs together for a paired test.
  4. Linear & Logistic Regression: Model Fitting with lm(), glm() & predict()
    Read the example and try it

    Fit a line using known trips, then predict for a new distance. The prediction uses the units of the training response.

    R script or RStudio console. Install any package named with :: before using its functions.

    trips <- data.frame(km=c(1,2,3), minutes=c(5,8,11))
    fit <- lm(minutes ~ km, data=trips)
    print(predict(fit, newdata=data.frame(km=4)))

    Choose models for a numeric score and a pass/fail flag.

    Outcomes are a numeric test score and a binary pass flag.

    Expected result
    One suitable pair is lm(score ~ minutes) for a continuous score and glm(pass ~ minutes, family=binomial()) for a binary outcome. The second model can predict probabilities.
  5. Reproducible Research & Dynamic Reporting: R Markdown, Quarto & Shiny
    Read the example and try it

    The document below prints the mean of two visit counts. Render it once, change the counts, then render it again. A fresh evaluation environment makes the source of each value explicit.

    Run this R script in a writable practice folder with rmarkdown and Pandoc installed. It creates visits.Rmd and visits.html.

    writeLines(c(
      "---", "title: Visits", "output: html_document", "---",
      "Mean: `r mean(counts)`"
    ), "visits.Rmd")
    
    render_visits <- function(values) {
      inputs <- new.env(parent = baseenv())
      inputs$counts <- values
      rmarkdown::render("visits.Rmd", envir = inputs, quiet = TRUE)
    }
    render_visits(c(2, 4))  # Open visits.html: Mean: 3
    render_visits(c(2, 8))  # Refresh visits.html: Mean: 5

    Render a report from fresh inputs and verify its summary changes.

    Render a report twice from fresh input, first counts 2,4 and then counts 2,8.

    Expected result
    The reported means change from 3 to 5. Render in a clean environment so a stale workspace value cannot keep the first result.

Trace changing state and check loop boundaries

A trace table records the state after each statement. It helps distinguish an incorrect algorithm from a syntax mistake. Write the input contract first: this example accepts a list of numbers and returns their sum. The initial total is zero, so an empty list returns zero.

Paper trace first; pseudocode is not executable. Use your chosen language compiler or interpreter for the implementation.

PSEUDOCODE — translate before running
total ← 0
FOR EACH value IN values
    total ← total + value
RETURN total
Check the output
[2, -1, 4] → 5
[] → 0
[7] → 7
The loop must process each element exactly once.

Trace [-3, 3] without running code. Then implement and test it. Explain why starting at the second element loses data. Reject non-number input or explicitly document that it is outside the input contract.

Avoid data leakage when preparing a dataset

A model evaluation is useful only when the held-out rows have not influenced training. Split the rows before learning a mean, scaler, vocabulary, or feature-selection rule. Fit those rules using training data, then reuse them unchanged on validation and test data. Time-ordered data often needs a chronological split instead of a random split.

Python 3; example uses no external packages

training = [10, None, 30]
testing = [None, 90]

observed = [x for x in training if x is not None]
mean = sum(observed) / len(observed)

def fill(values):
    return [mean if x is None else x for x in values]

print(fill(training))
print(fill(testing))
Check the output
[10, 20.0, 30]
[20.0, 90]

Explain why including 90 when computing the replacement mean leaks information. Decide what to do if every training value is missing.

Make a small learning project reproducible

A project is reproducible when another learner can obtain the same inputs, install the required tools, and repeat your checks. Record the tool versions and exact run commands. Use synthetic or permission-cleared sample data. Keep credentials outside the repository. A successful run on your laptop is a starting point; a fresh environment is a better check.

Any language; choose the package and build tools appropriate to that course

study-project/
  README.md          # setup, run, test, expected result
  src/               # your implementation
  tests/             # behavior checks
  data/              # small synthetic example data
  .gitignore         # caches, build output, local secrets
Check the output
This is a suggested directory layout, not a command to execute. Adapt conventions to the chosen language.

Build a score summarizer. Include an empty-input test, a malformed-input test, and one example whose answer can be calculated by hand.

Check an R result with stopifnot

A data-analysis script should verify its assumptions before producing a chart or report. stopifnot raises an error when a condition is not true. Floating-point comparisons need a tolerance, so use isTRUE(all.equal(...)) rather than expecting exact equality for every decimal calculation.

R; base functions only

total <- function(values) {
  sum(values)
}

stopifnot(total(c(4, 6)) == 10)
stopifnot(total(numeric(0)) == 0)
stopifnot(isTRUE(all.equal(total(c(0.1, 0.2)), 0.3)))
cat("Checks passed\n")
Check the output
Checks passed

Add an NA value and decide whether missing observations should be rejected, propagated, or removed. Make the policy explicit in the function.

Handle runtime errors and exceptions in R with tryCatch

In production R pipelines, uncaught errors halt entire batch processing scripts. The tryCatch function intercepts conditions, allowing you to return a fallback value, log an informative warning, and keep running cleanly.

R statistical environment; base package only

safe_divide <- function(x, y) {
  tryCatch(
    expr = {
      if (y == 0) stop("Cannot divide by zero")
      x / y
    },
    error = function(e) {
      NA_real_
    }
  )
}
cat(safe_divide(10, 2), safe_divide(10, 0), "\n")
Check the output
5 NA

Extend the error handler to also catch warnings when converting character strings to numbers using as.numeric().

Open the R learning path on DevStudyHub · Play coding games on this blog

logoblog

No comments:

Post a Comment

Please do not enter any spam link in the comment box.