7  Preparing Data in R

NoteWhat you’ll be able to do

By the end of this chapter you will be able to:

  1. Load a dataset and inspect it with str(), head(), and summary().
  2. Create the recoded babies variables (smoke_bi, par_bi, age_group) with the standard prep script.
  3. Convert variables to their correct types, especially 0/1 codes to factors.
  4. Spot the common preparation pitfalls before they corrupt an analysis.

Before you run any statistical test, your data have to be clean and in the right format. Variables stored as the wrong type, missing values handled badly, or categorical columns left as text strings — any of these can cause R to refuse to run your test, or worse, to run something subtly wrong without complaint.

This chapter is the routine you’ll repeat at the start of every analysis: import the data, inspect it, fix variable types, and check for missing values. Five minutes here saves hours later.

Throughout this chapter we’ll use the Baby Dataset — birth-weight data for 1,236 infants along with maternal characteristics. You will return to this dataset across several later chapters and assignments, so the examples here double as your first introduction to it.

7.1 Storing things in R

Before importing anything, you need to understand how R holds information in memory.

When you run:

babies <- read.csv("some_data.csv")

you are doing two things at once: loading a dataset and storing it in memory under the name babies. The arrow <- is the assignment operator — it takes whatever is on the right and stores it under the name on the left. (For this book’s Baby Dataset you won’t need a file or URL at all — it comes from the UsingR package, as shown in Step 1 — but the <- idea is the same.)

The name is yours to choose. babies, data, my_data, d — all would work. But the name you use here is the name you must use everywhere else. If you store the dataset as babies and then write mean(baby$bwt), R will tell you it has never heard of baby. This is one of the most common beginner errors, and it is entirely about spelling.

TipNaming conventions
  • Use lowercase letters and underscores: my_data, babies, study_1
  • Avoid spaces and special characters: my data won’t work as a name. Dots are legal (my.data), but underscores are the easier habit
  • Make names descriptive enough to recognize but short enough to type: babies is better than b and also better than the_infant_birth_weight_dataset_2024

7.2 Step 1: Load and inspect your data

Load the Baby Dataset from the UsingR package:

library(UsingR)
data(babies)

No file uploading or URL required — the dataset lives inside the package. If you get “there is no package called ‘UsingR’”, run install.packages("UsingR") once first, then load it.

Important: before running any analysis, the data need cleaning. The published dataset uses terse column names (wt, ht, wt1) and missing-value codes (999 for most numeric variables, 99 for some, 9 for categorical ones) — not R’s standard NA. The block below does two jobs at once: it recodes those missing values to NA and creates the clearly-named, analysis-ready columns the rest of this book uses (bwt, height, weight, smoke_bi, par_bi, age_group).

# Recode missing values and create clean, clearly-named columns
babies$bwt       <- ifelse(babies$wt == 999, NA, babies$wt)               # birth weight (oz)
babies$gestation <- ifelse(babies$gestation == 999, NA, babies$gestation) # gestation (days)
babies$age       <- ifelse(babies$age == 99, NA, babies$age)             # mother's age (yr)
babies$height    <- ifelse(babies$ht == 99, NA, babies$ht)               # mother's height (in)
babies$weight    <- ifelse(babies$wt1 == 999, NA, babies$wt1)            # mother's weight (lb)
babies$smoke     <- ifelse(babies$smoke == 9, NA, babies$smoke)          # 0/1/2/3 (9 = unknown)

# Binary smoking variable: 1 = smokes now, 0 = never (drops the in-between categories)
babies$smoke_bi  <- ifelse(babies$smoke %in% c(0, 1), babies$smoke, NA)
# Binary parity: 0 = first-time mother, 1 = has given birth before
babies$par_bi    <- ifelse(babies$parity == 0, 0, 1)
# Age group: 1 = teens (≤19), 2 = 20s, 3 = 30+
babies$age_group <- cut(babies$age, breaks = c(0, 19, 29, 99), labels = c(1, 2, 3))

Run summary(babies) after this step. The columns this block touches now show their NA counts instead of impossible values like gestation = 999 days. You now have clean bwt, height, weight, smoke_bi, par_bi, and age_group columns to work with.

The block cleans only the columns this book uses. Other raw columns still carry their codes: the father’s height (dht) and weight (dwt) still show 99 and 999, and family income (inc) shows 98. So summary() will still show some impossible-looking maximums. Leave those columns alone, or recode them the same way before you use them.

Once the data is loaded and cleaned, run these three commands:

str(babies)      # variable names, types, and a preview
summary(babies)  # five-number summary plus mean for each variable
head(babies)     # the first six rows

These three together tell you what you have. Read the output before you do anything else.

7.2.1 Reading str() output

str() shows each column with an abbreviation for its type. The ones to know:

Abbreviation Stands for Example values
num Numeric (decimal) 5.2, 10.0, 3.14
int Integer (whole number) 1, 2, 3
chr Character (text) “Yes”, “No”, “Male”
Factor w/ 3 levels Factor (categorical variable) “Group A”, “Group B”
logi Logical (TRUE/FALSE) TRUE, FALSE

After cleaning, every Baby Dataset column shows as num, including the grouping variables you just created: smoke_bi and par_bi hold 0s and 1s even though they represent categories (smoker / non-smoker). You convert them to factors in Step 2. (age_group, built with cut(), is already a factor.)

TipQuick mental model
  • Numeric or integer (num, int): the dependent variable (DV) in t-tests, ANOVA, and regression.
  • Factor (fct): the independent/grouping variable in t-tests and ANOVA, and either side in chi-square.
  • Character (chr): almost always needs to be converted to a factor before you analyze it.

If str(babies) shows a categorical column as chr, int, or num, you have a job to do.

7.3 Step 2: Access columns and fix variable types

7.3.1 The $ operator

babies$smoke means “the smoke column inside the babies data frame.” The $ is how R navigates inside a named object. The name before $ must exactly match the object you created; the name after $ must exactly match a column in that object.

babies$bwt        # the birth weight column
babies$smoke      # the smoking status column
babies$gestation  # the gestation length column

7.3.2 Converting variable types

R lets you change a variable’s type with a small family of as.*() functions.

# Convert the binary smoking variable to a factor — it's stored as 0/1
babies$smoke_bi <- as.factor(babies$smoke_bi)

# Same for the binary parity variable (0 = first-time mother, 1 = experienced)
babies$par_bi <- as.factor(babies$par_bi)

# age_group is already a factor (cut() created it that way) — confirm with str()

After any conversion, run str(babies) again to confirm the change took effect.

Why bother, if 0 and 1 already look like two groups? t.test() would actually cope: it treats any two-valued column as two groups. aov() and lm() don’t. Give them a numeric group code and they fit a straight line through the codes instead of comparing the groups. With age_group stored as the numbers 1, 2, 3, aov() reports 1 degree of freedom where a three-group comparison has 2. There is no error and no warning, just the wrong analysis. Converting to a factor is how you tell R “these are categories, not amounts.”

WarningA subtle pitfall

as.numeric() applied directly to a factor returns the level numbers (1, 2, 3, …), not the labels. That matters when the labels look like numbers:

scores <- factor(c("70", "80", "90", "80"))
as.numeric(scores)                 # 1 2 3 2   — level numbers, not scores
as.numeric(as.character(scores))   # 70 80 90 80 — the actual values

Go through as.character() first to get the values back. This bites everyone at least once.

7.4 Step 3: Match variables to the right test

Once your variable types are correct, the test you should run is determined by them. This is just Table 2.1 from Chapter 2 restated as an R-syntax recipe:

Test DV (outcome) IV (predictor) R syntax
t-test numeric factor with 2 levels t.test(Score ~ Group, data = data)
ANOVA numeric factor with 3+ levels aov(Score ~ Condition, data = data)
Regression numeric numeric or factor (or both) lm(Score ~ Age + Group, data = data)
Chi-square factor factor chisq.test(table(data$Gender, data$Preference))

When a variable has the wrong type, R doesn’t always complain. A character outcome in t.test() fails with a confusing message (missing value where TRUE/FALSE needed), but a numeric grouping variable in aov() or lm() runs without complaint and answers the wrong question (Step 2). If a result looks odd, or the df don’t match the number of groups, check str() first.

7.5 Step 4: Handle missing values

Real data have gaps. R represents a missing value as NA (not the same as the string "NA" or zero).

7.5.1 Find the missing values

summary(babies)             # NA counts are shown for each variable
colSums(is.na(babies))      # count of NAs per column

summary() is the quick check; colSums(is.na(babies)) is more precise when you want exact counts.

7.5.2 Decide what to do about them

Option 1: Listwise deletion (drop every row with any NA). Simple, but throws away data — sometimes a lot of it.

babies_complete <- na.omit(babies)
nrow(babies) - nrow(babies_complete)   # how many rows did we lose? 253

Be careful what you hand to na.omit(): it drops a row if any column is missing. On the whole Baby Dataset that costs 253 rows, and 198 of them are mothers who quit smoking (codes 2 and 3). smoke_bi leaves them out on purpose, so for any other question they aren’t missing data at all. For a question about gestation and birth weight, keep just those columns first:

gest_data <- na.omit(babies[, c("bwt", "gestation")])
nrow(babies) - nrow(gest_data)   # 13 rows lost, not 253

Option 2: Per-analysis exclusion. The model functions skip NAs automatically: t.test(), aov(), and lm() drop any row that is missing a variable in that analysis, and nothing else.

The simple summary functions don’t. mean(), sd(), and median() return NA if even one value is missing, unless you tell them to skip it:

mean(babies$gestation)                # NA — 13 values are missing
mean(babies$gestation, na.rm = TRUE)  # 279.3385

na.rm = TRUE means “remove NAs before calculating.” You’ll use it constantly.

Option 3: Imputation. Replace NAs with estimated values (mean, median, or a model-based estimate). This is appropriate in some cases but is more invasive than this course typically requires — we’ll stick with options 1 and 2.

ImportantDon’t pretend missing values don’t exist

A drop from 100 rows to 60 because of NAs is not just a cosmetic issue. It changes your sample size, your power, and your effect estimates. Always report how many cases were excluded and why. If a particular variable has more than ~20% missing, treat that as a finding in itself and find out why. The people who skipped a question may differ from the people who answered it.

7.6 Step 5: Spot-check the data

Before you trust a p-value, you should trust the data underlying it. Look at:

  • Variable ranges in summary() — does any variable have an impossible min or max? (Age = 300, score = −50, percentage > 100.)
  • The actual data with View(babies) — opens a spreadsheet view in RStudio. Useful for catching weird codings like 99 meaning “missing.”
  • Histograms and boxplots — covered in detail in Chapter 8, but a quick hist(babies$bwt) will reveal extreme outliers or bimodal distributions you’d miss in summary().

7.7 Final checklist before analysis

A short list to run through every time:

If every box is checked, you’re ready to test.

7.8 Common errors — what they mean and how to fix them

R error messages look alarming but almost always name the problem precisely. Here are the four errors you will hit most often working with this dataset.

7.8.1 Error 1: Object not found

mean(baby$bwt)
Error: object 'baby' not found

R is telling you it has no object called baby in memory. Earlier you stored the dataset as babies (plural). R object names must match exactly — baby and babies are completely different names to R.

mean(babies$bwt)   # correct

General lesson: When R says “object not found,” check the spelling of your object name. Run ls() to see what is actually in memory.


7.8.2 Error 2: Column not found

mean(babies$birthweight)
[1] NA
Warning message:
In mean.default(babies$birthweight) :
  argument is not numeric or logical: returning NA

This one is sneaky: R doesn’t stop. Asking for a column that doesn’t exist gives you NULL (nothing), and mean() of nothing comes back as NA with only a warning. The column is named bwt, not birthweight. Run names(babies) to see the exact column names — then copy-paste from the output rather than typing from memory.

mean(babies$bwt)   # correct

General lesson: When a result comes back NA or NULL and you didn’t expect it, check names(babies) and verify the exact spelling.


7.8.3 Error 3: Forgot data =

boxplot(bwt ~ smoke_bi)
Error in eval(predvars, data, env) : object 'bwt' not found

R is looking for a standalone object called bwt in your environment. It exists as a column inside babies, but R does not know to look there unless you tell it.

boxplot(bwt ~ smoke_bi, data = babies)   # correct

General lesson: Functions that use formula syntax (outcome ~ group) almost always require a data = argument that tells R where to find the variables.


7.8.4 Error 4: Grouping variable doesn’t have exactly two levels

t.test(bwt ~ smoke, data = babies)
Error in t.test.formula(bwt ~ smoke, data = babies) : 
  grouping factor must have exactly 2 levels

The raw smoke column has four categories (0, 1, 2, 3), not two. A t-test compares exactly two groups, so use the binary version you created during cleaning, smoke_bi (0 = never, 1 = smokes now):

t.test(bwt ~ smoke_bi, data = babies)   # now works correctly

Converting smoke to a factor wouldn’t help: it would still have four levels.

General lesson: When a grouping variable causes problems, count its groups with table(babies$smoke). A t-test needs exactly two; for three or more, you need ANOVA, with the grouping variable stored as a factor.

7.9 Getting help from AI

AI assistants are useful for decoding R errors. A good debugging prompt:

I am learning R for statistics. I got this error: [paste error]. Here is my code: [paste code]. Please explain what the error means and give me a hint, but do not complete the assignment for me.

A poor prompt:

Here is my assignment. Do it for me.

The goal is to understand what went wrong — not to get code that bypasses the question. If you copy-paste an AI-generated interpretation without checking it against your actual output, you will not be able to answer follow-up questions about it.

7.10 Template prep script for the Baby Dataset

Save this as the first thing in every analysis script that uses the Baby Dataset.

# 1. Load
library(UsingR)
data(babies)

# 2. Inspect BEFORE cleaning — spot the 999s
str(babies)
summary(babies)
head(babies)

# 3. Recode missing values and create clean, clearly-named columns
babies$bwt       <- ifelse(babies$wt == 999, NA, babies$wt)
babies$gestation <- ifelse(babies$gestation == 999, NA, babies$gestation)
babies$age       <- ifelse(babies$age == 99, NA, babies$age)
babies$height    <- ifelse(babies$ht == 99, NA, babies$ht)
babies$weight    <- ifelse(babies$wt1 == 999, NA, babies$wt1)
babies$smoke     <- ifelse(babies$smoke == 9, NA, babies$smoke)
babies$smoke_bi  <- ifelse(babies$smoke %in% c(0, 1), babies$smoke, NA)
babies$par_bi    <- ifelse(babies$parity == 0, 0, 1)
babies$age_group <- cut(babies$age, breaks = c(0, 19, 29, 99), labels = c(1, 2, 3))

# 4. Fix variable types (grouping variables → factors)
babies$smoke_bi  <- as.factor(babies$smoke_bi)
babies$par_bi    <- as.factor(babies$par_bi)

# 5. Check for missing values after cleaning
colSums(is.na(babies))

# 6. Sanity-check distributions
hist(babies$bwt)
boxplot(babies$bwt ~ babies$smoke_bi)

# 7. Verify final structure
str(babies)

Once your data are clean and the variables are the right types, you’re ready to start producing plots — which is the next chapter.


TipChapter Summary

Core idea: The five minutes you spend inspecting and cleaning your data before analysis will prevent hours of confusing errors afterward. Variable type problems, missing values, and stray factor levels are invisible until they break something.

You should understand:

  • Why R distinguishes between numeric, character, and factor variables — and why that distinction matters for analysis
  • What the <- operator does and why spelling matters
  • What missing values (NA) are, how R handles them by default, and when that default causes problems
  • Why you should always run str() and summary() before any analysis

You should be able to do in R:

  • Load a package dataset: library(UsingR); data(babies)
  • Inspect: str(babies), summary(babies), head(babies)
  • Access a column: babies$bwt
  • Fix variable types: babies$smoke_bi <- as.factor(babies$smoke_bi)
  • Check for missing values: colSums(is.na(babies))

Plain-language check: After cleaning, str() shows a grouping variable as num. A classmate runs aov(bwt ~ age_group_num, data = babies) on a version of age_group stored as the numbers 1, 2, 3, and gets 1 df for the groups. Why 1 and not 2, and what is the fix? And why didn’t the t-test in Error 4 need the same fix?

The one mistake to avoid: Assuming the import worked correctly without checking. Columns that look categorical can import as integers; a typo in your object name creates a new error rather than editing the old one. Always inspect before proceeding.

Practice: Run library(UsingR); data(babies). Then run summary(babies). Do you see any impossible values? Recode the missing values, convert the categorical variables to factors, and run summary(babies) again. What changed?

Key terms from this chapter are defined in the Glossary.

NotePractice: Cleaning Messy Data

Put this chapter to work on a realistic messy dataset: Ch 7 Extension: Cleaning Messy Data. It opens with the exact “grouping factor must have exactly 2 levels” error from above, then asks you to find and fix every problem in the data before running the analysis for real.