01 / 19
?

Stating
Assumptions in R

Learn to explicitly declare what you assume about data types, missingness, and units before writing a single line of analysis code.

R Programming

What Are Data Assumptions?

An assumption is a belief about your data that you accept as true before analysis. Every dataset carries hidden expectations: that ages are numeric, that prices are in dollars, that no values are missing. If any assumption is wrong, your entire analysis can silently produce incorrect results.

The Three Pillars of Assumptions

Data Types
Is each column numeric, character, factor, logical, or date? R silently coerces types, which can hide errors.
Missingness
Are there NA values? How many? Are they random, or do they follow a pattern that biases results?
Units
Is height in centimeters or inches? Is currency in USD or EUR? Mixing units causes catastrophic miscalculations.

Why Stating Assumptions Matters

Raw Data State Assumptions Types ✓ Missing ✓ Units ✓ Range ✓ Reliable Analysis Skip Assumptions Silent Errors Data Analysis Pipeline Two paths: explicit assumptions vs. silent failure

The Assumption Statement Rule

Before any analysis, write a comment block in your R script that explicitly states every assumption. Then write code that tests each one. If a test fails, stop the analysis and investigate.

# ASSUMPTIONS:
# 1. `age` is numeric (integer or double)
# 2. `age` has no NA values
# 3. `age` is in years (not months)
# 4. `price` is in USD

# TESTS:
stopifnot(is.numeric(df$age))
stopifnot(!any(is.na(df$age)))
stopifnot(all(df$age >= 0 & df$age <= 150))

Implicit vs. Explicit Assumptions

Implicit (Dangerous) Explicit (Safe)
Visibility Hidden in your head Written in code comments
Testable? No: you forget to check Yes: stopifnot() validates
When caught After wrong results published Before analysis runs
Reproducibility Others can't see your logic Fully documented for collaborators
Example "I guess weight is in kg" # Assume weight in kg, range 0-300

Pillar 1: Data Type Assumptions

R Data Types numeric integer double character factor Date logical TRUE/FALSE Danger: "123" looks numeric but is character. R won't warn you!

Pillar 2: Missingness Assumptions

MCAR
Missing Completely at Random: the missingness has no pattern. Safe to drop rows.
MAR
Missing at Random: missingness depends on other observed variables. Imputation is possible.
MNAR
Missing Not at Random: missingness depends on the missing value itself. Very dangerous to ignore.
# Check missingness per column
colSums(is.na(df))

# Assumption: income has \(< 5\%\) NA
stopifnot(mean(is.na(df$income)) < 0.05)

Pillar 3: Unit Assumptions

Unstated Units height = 72 Inches? Centimeters? Feet? Millimeters?
\(\text{mean(height)} = \text{???}\)
Stated Units height_inches = 72 Unit is in the name Comment documents it
\(\text{mean} = 68.5 \text{ inches } \checkmark\)

How to State Assumptions: Checklist

1
Inspect the data. Run str(df), summary(df), and head(df) to see what you actually have.
2
Write a comment block. List every assumption about types, missingness, units, and valid ranges at the top of your script.
3
Add assertion code. Use stopifnot() or if/stop() to validate each assumption programmatically.
4
Handle violations. If an assumption fails, decide: clean the data, transform it, or document the limitation.
5
Re-check after cleaning. After any transformation, re-run your assertions to confirm assumptions still hold.

Example 1: Student Grades Dataset

You receive a CSV with columns name, grade, and gpa. Before computing average GPA, state your assumptions.

# Load data
students <- read.csv("students.csv")

# ASSUMPTIONS:
# 1. `name` is character
# 2. `grade` is integer (9, 10, 11, 12)
# 3. `gpa` is numeric, range \([0.0, 4.0]\)
# 4. No NA values in gpa
# 5. GPA is on a 4.0 scale (not 5.0)

# VALIDATE:
stopifnot(is.character(students$name))
stopifnot(is.numeric(students$gpa))
stopifnot(all(students$gpa >= 0 &
            students$gpa <= 4.0,
            na.rm = TRUE))
stopifnot(!any(is.na(students$gpa)))

Example 2: Weather Sensor Data

A weather station logs timestamp, temp, and humidity every hour. You want to compute daily averages.

# ASSUMPTIONS:
# 1. `timestamp` is POSIXct (not character)
# 2. `temp` is numeric, in Celsius
# 3. `temp` range: \([-50, 60]\) (reasonable)
# 4. `humidity` is numeric, range \([0, 100]\) (%)
# 5. Rows are hourly: \(\sim 24\) per day
# 6. Missing readings \(< 10\%\) per day

stopifnot(inherits(weather$timestamp,
            "POSIXct"))
stopifnot(all(weather$temp >= -50 &
            weather$temp <= 60,
            na.rm = TRUE))

Example 3: E-Commerce Transactions

An online store exports order_id, product, quantity, price, and currency. You need to compute total revenue.

# ASSUMPTIONS:
# 1. `price` is numeric, non-negative
# 2. `currency` is all "USD" (single currency)
# 3. `quantity` is positive integer
# 4. No duplicate order_id values
# 5. No NA in price or quantity

stopifnot(all(orders$currency == "USD"))
stopifnot(!any(duplicated(orders$order_id)))
stopifnot(all(orders$quantity > 0))
stopifnot(all(orders$price >= 0))

R Functions for Checking Assumptions

What to Check R Function Returns
Column type class(x), is.numeric(x) Type name / TRUE-FALSE
All types at once str(df) Structure summary
Missing values is.na(x), sum(is.na(x)) Logical vector / count
Value range range(x), summary(x) Min and max / stats
Unique values unique(x), length(unique(x)) Distinct values / count
Assert condition stopifnot(cond) Error if FALSE

Common Mistakes

✕ Assuming No NAs
Running mean(x) without na.rm = TRUE returns NA if any value is missing. Always check first.
✕ Trusting Column Names
A column called "age" might contain character strings like "25 years". Verify the actual type, not the label.
✕ Ignoring Mixed Units
Merging datasets where one uses kg and another uses lbs creates nonsensical averages. State and verify units.

Question 1 of 5

Which R function would you use to halt your script if an assumption is violated?

Question 2 of 5

A column called zip_code contains values like "02134". What data type assumption should you state?

Question 3 of 5

You discover that 40% of income values are NA, and all missing values come from respondents who declined to answer. This missingness pattern is:

Question 4 of 5

You merge two datasets: one records weight in kilograms, the other in pounds. Both columns are named "weight". What is the best first step?

Question 5 of 5

Which unstated assumption most likely caused the NA result?