Business Analytics & Data Science

B02 · Introductory

Data Cleaning and Preparation

12 lessons

B02 · Module 1, lesson 1 · Lesson 1 of 12

Datasets: rows, columns, records and variables

Before you clean or analyse a table, describe it exactly: what one row is, what kind of value each column holds, which column identifies each row, and what every column is supposed to contain. Get this wrong and correct arithmetic gives the wrong answer.

About 75 minutes

Before you start

You will be able to

  • Identify the observations, variables and unit of observation of a dataset, and explain why the unit changes the answer to a question.
  • Recognise tidy and untidy layouts, and describe what makes a layout untidy.
  • Classify a variable as nominal, ordinal, interval or ratio, and as discrete or continuous, and state which comparisons and summaries it supports.
  • Choose a primary key or composite key for a table and test whether it identifies every row.
  • Write a data dictionary entry that defines a column’s meaning, level, type, unit and rules.
  • Distinguish wide and long layouts of the same data.

Review first

  • No earlier lesson. You should be able to open a spreadsheet, scroll through a table and sort a column.

Fictional case A fictional coffee business founded by Ana Lim. It starts as a catering and barista-training service, opens its own cafés and an online shop for beans, and plans a canned cold brew.

The idea

This course treats data cleaning as a chain of decisions you can explain and repeat, not a bag of tricks: you will look before you change anything, and you will write down why. It starts where every analysis should, by describing exactly what a table contains.

Fictional case

Lantern Coffee Co., Ana Lim’s coffee business, now sells beans and subscriptions through an online shop. After the shop’s first four months Ana asks a question that sounds simple: what is the average order worth? Three people give her three different answers from the same export, and all three did their arithmetic correctly. They disagreed about something more basic: what one row of the file represents.

Rows, columns and cells

A dataset is a collection of values organised so that each value describes one characteristic of one thing. In a table, the things are the rows and the characteristics are the columns. Each row is an observation, also called a record: everything recorded about one instance of what is being studied, such as one order, one booking or one student. Each column is a variable, also called a field or an attribute: one characteristic recorded for every observation, such as the order date or the quantity. A cell holds a single value: one variable for one observation.

Different disciplines use different words for the same parts, and you will meet all of them in documentation and software:

The same three parts of a table under four names
PartStatisticsDatabasesSpreadsheetsMachine learning
A rowobservationrecord, row (tuple in relational theory)rowexample, instance or sample
A columnvariablefield, attribute, columncolumnfeature
A cellvaluevaluecellfeature value

What does one row describe?

The unit of observation is the kind of thing that one row describes. It is the first fact to establish about any table, because counts, totals and averages are all counted in units of it. Lantern’s shop can export a line-item report with one row for each product on each order, so an order for two packs of House Blend and one of Decaf Colombia takes two rows. Here are four orders from that report:

Part of Lantern’s line-item report: one row per product on an order (fictional)
order_idlinecustomer_idproductqtyline_total ($)
10011C01House Blend 250g228.00
10012C01Decaf Colombia 250g116.50
10021C02Cold Brew Pack122.00
10031C01House Blend 1kg146.00
10032C01Ethiopia Yirgacheffe 250g119.50
10033C01Decaf Colombia 250g116.50
10041C03Ethiopia Yirgacheffe 250g119.50
Total (7 rows)8168.00

Ask “what is the average order worth?” and this table gives three different answers. Averaging the line_total column gives 168÷7=24.00168 \div 7 = 24.00 dollars, which is the average line, not the average order. Adding up the lines within each order first gives four order totals ($44.50, $22.00, $82.00 and $19.50), and their average is 168÷4=42.00168 \div 4 = 42.00 dollars. Adding up within each customer instead gives an average of 168÷3=56.00168 \div 3 = 56.00 dollars per customer. Each number is correct and each answers a different question. Only the second is the average order value, and you can find it only if you know that the rows are order lines.

Counts fall into the same trap. The table has seven rows, but it records four orders, three customers and eight packs of coffee. Whenever you count, total or average, say what you are counting: the number of rows is the answer only when the rows are the things you care about.

Tidy data

Tables arrive in many layouts, and some make analysis much harder than others. Hadley Wickham (2014) described a standard layout, which he called tidy data, built on three rules:

  1. Each variable forms a column.
  2. Each observation forms a row.
  3. Each type of observational unit forms a table.

The rules sound obvious, yet business files break them constantly, because files are often laid out for people to read rather than for software to analyse. Wickham lists five common ways a table can be untidy: column headers that are values rather than variable names, such as one column per month; several variables stored in one column, such as “Ethiopia-500g” holding both the product and the pack size; variables stored in both rows and columns; several types of observational unit in one table; and one type of observational unit spread across several tables, such as a separate file for each month.

Lantern’s line-item report is tidy for questions about lines: one row per line and one column per variable. Its customer_id column points to a second observational unit, the customer, and facts about customers, such as an email address, belong in a customer table where each is stored once. Exports often break the third rule on purpose, repeating customer details on every order so that one file is enough. That is convenient, but the same fact is then stored many times and the copies can disagree, which you will learn to check for in the next lesson.

Kinds of variables

What you can sensibly do with a variable depends on what its values mean, not on whether they look like numbers. The first split is between categorical and numerical variables. A categorical variable places each observation in a group: the region an order is delivered to, the channel it came through, whether it belongs to a subscription. A numerical variable records an amount found by counting or measuring: the quantity ordered, the unit price, the pack size in grams.

Each kind splits again. A nominal variable is categorical with no natural order: North is neither more nor less than South. An ordinal variable is categorical with a meaningful order but no fixed distance between categories: on a 1–5 rating, 4 is better than 3, but nothing says the step from 3 to 4 equals the step from 4 to 5. A discrete variable is numerical and takes separate values with gaps between them, usually because it counts something: 1, 2 or 3 packs, never 2.4. A continuous variable can take any value within a range, at least in principle, usually because it is measured: weight, time, distance.

Some cases need judgement. Money is recorded to the cent, so strictly it is discrete, but it has so many possible values that analysts treat it as continuous. Lantern’s pack size is a measured weight, yet the shop sells only a few sizes, so in most analyses it behaves like a small set of groups. Classify a variable by how you will use it, and say so when the choice isn’t obvious.

The line-item report’s columns, classified
ColumnKindWhy
order_idCategorical, nominal (an identifier)A label for the order; its digits are not an amount.
lineCategorical (a label for a position within the order)Line 2 is not “twice” line 1; with order_id it names one row.
customer_idCategorical, nominal (an identifier)Points to a customer.
productCategorical, nominalNames a product.
qtyNumerical, discreteCounts packs.
line_total ($)Numerical, continuous in practiceAn amount of money.

Numbers that are not quantities

order_id is written with digits, yet it is not a number in any useful sense. Order 1004 is not “three more” than order 1001, and the average order number means nothing. Identifiers, postcodes, phone numbers and product codes are labels that happen to use digits. A quick test: if adding two values or averaging them makes no sense, the variable is categorical, whatever characters it uses. Store such columns as text, too. A spreadsheet that reads the code 02134 as a number drops the leading zero and stores 2134, which is a different label.

In depth

Levels of measurement

In 1946 the psychologist S. S. Stevens proposed classifying measurements by the operations that make sense on them. His four levels of measurement are still taught in introductory statistics. Each level allows everything the levels below it allow, plus one more kind of comparison.

Stevens’s four levels of measurement
LevelYou can sayMeaningful summariesExamples
NominalSame or differentCounts, proportions, the moderegion, channel, product, customer_id, a postcode
OrdinalAlso: greater or lessAlso: the median and percentilesa 1–5 rating; roast (light, medium, dark); a hotel’s star category
IntervalAlso: by how much (differences)Also: the mean and standard deviationorder_date; temperature in °C or °F
RatioAlso: how many times (ratios)Also: ratios such as the coefficient of variationquantity, unit price, order total, pack size, nights stayed

Each row allows everything in the rows above it. Summaries follow Stevens’s table of “permissible statistics” (1946).

Interval and ratio variables are both numerical; the difference is the zero. On a ratio variable zero means none of the quantity, so ratios are meaningful: an order of 4 packs is twice an order of 2. On an interval variable differences are meaningful but zero is an arbitrary point on the scale, so ratios are not. Calendar dates are interval: 15 May is 14 days after 1 May, but no date is “twice” another, because where a calendar starts counting is a convention.

Temperature in degrees Celsius is the classic case: 20 °C is not twice as warm as 10 °C. Convert both to Fahrenheit and they become 68 °F and 50 °F, a ratio of 68÷50=1.3668 \div 50 = 1.36; in kelvin, which starts at absolute zero, they are 293.15 K and 283.15 K, a ratio of about 1.035. A ratio that changes when you move the scale’s zero was never meaningful.

Durations are different from dates. The number of days between two dates is a ratio variable, because zero days means no time at all: a 6-night stay is twice as long as a 3-night stay. That is why Harborview Hotel’s nights column is ratio although its check_in column is interval.

Do the levels forbid calculations?

Stevens argued that, in the strictest sense, means and standard deviations should not be used with ordinal data, because the steps between categories need not be equal. He also acknowledged that such statistics often prove useful in practice. Online shops average star ratings all the time, and an average of 4.2 is a reasonable quick summary. What an average hides is the shape: an average of 3 can come from every customer giving 3, or from half giving 1 and half giving 5, and those describe very different businesses. When you average an ordinal variable, report its distribution or its median too.

Velleman and Wilkinson (1993) went further, arguing that the level of measurement is not a fixed property of the data but depends on the question being asked. Lantern’s order numbers are nominal when you use them to look up an order; if the shop issues them in sequence, comparing two of them tells you which order was created first, which is an ordinal use. Treat the levels as a check on whether a calculation means anything, not as a rule that software should enforce.

Identifiers and keys

To find, count, correct or link rows you need a way to say which row is which. A primary key is a column, or a set of columns, whose values identify each row uniquely. Two conditions define it: no two rows share a value, and no row is missing one. Relational databases enforce both; PostgreSQL, for example, requires a primary key’s values to be unique and not null. Exports and spreadsheets enforce nothing, so you have to check.

Sometimes no single column is enough. In Lantern’s line-item report order_id repeats (one order has several lines) and line repeats (every order has a line 1), but each pair of order_id and line appears only once. A key made of two or more columns is a composite key. Choosing a key is the same decision as naming the unit of observation: if one row is one order line, the key must identify order lines.

To test a candidate key, count the rows, nn; count the distinct values of the candidate (for a composite key, the distinct combinations); and count the rows where any part of it is blank. The candidate is a key for this table only if the distinct count equals nn and the blank count is zero. In SQL, SELECT COUNT(*), COUNT(DISTINCT order_id) FROM orders; returns both counts. In pandas, df.order_id.is_unique tests uniqueness and df.order_id.isna().sum() counts blanks. In a spreadsheet, compare the count of the column with the count of its unique values.

A key that passes proves only that this file has no repeats. Whether a repeat could arrive is a question about how the data is created, and the lesson on duplicates returns to it. Good keys are stable and meaningless. A customer’s email address seems to identify them, but people change addresses, couples share one, typing errors create a second version and some orders have no email at all. That is why systems issue identifiers such as customer_id, which never change and carry no meaning that could go out of date. When customer_id also appears in an orders table, it links each order to one row of the customer table; a column used this way is called a foreign key, and the next lesson shows how to check that every link points somewhere.

The data dictionary

A data dictionary records what each column of a dataset is supposed to contain. The US Geological Survey describes it as a way to catalogue and communicate a dataset’s structure and content. Typical entries give each element’s name and definition, its data type and size, whether it may be blank, its allowed values, the codes used for missing data and the business rules it must obey. Add the unit of measurement and, for calculated columns, how they are calculated.

Writing the dictionary is where vague columns get pinned down. “discount” could be a percentage or a dollar amount, per pack or per order; “order_date” could be when the order was placed, paid for or shipped. Below is a draft for Lantern’s full order export, the dataset called lantern-orders that you will clean in this course. It records what each column should contain. The export doesn’t always comply, and finding where it doesn’t is the subject of the next lesson.

Draft data dictionary for Lantern’s order export (fictional)
ColumnMeaningLevelType and unitRules
order_idIdentifies the orderNominal (the key)TextRequired; unique: one row per order
order_dateDate the customer placed the orderIntervalDate, written YYYY-MM-DDRequired; within the period exported
customer_idIdentifies the customer who placed itNominalTextRequired; must exist in the customer table
emailCustomer’s email address at the time of the orderNominalTextRequired (receipts are emailed); one @ followed by a domain
regionDelivery regionNominalTextRequired; one of the names in Lantern’s list of regions
productCoffee orderedNominalTextRequired; a product name from the catalogue
size_gPack sizeRatioNumber, gramsRequired; a size the catalogue sells
quantityPacks orderedRatio (discrete)Whole number, packsRequired; at least 1
unit_priceList price of one packRatioNumber, dollarsRequired; greater than 0
discountMoney taken off the whole orderRatioNumber, dollarsRequired; 0 if none; at most quantity × unit_price
order_totalAmount charged for the orderRatioNumber, dollarsRequired; equals quantity × unit_price − discount, to the cent
channelWhere the order was placedNominalTextRequired; one of Lantern’s channel names
subscriptionWhether the order is a subscription deliveryNominal (yes/no)Yes or noRequired; two values only
ratingCustomer’s rating of the orderOrdinalWhole number, 1–5Optional: blank if the customer didn’t rate

Notice what the dictionary settles. Email is required but rating is optional, so a blank rating is normal and a blank email is a defect. Discount is defined in dollars for the whole order, which turns order_total into something you can check from the other columns. And unit_price is declared a number, which, as the next lesson shows, the raw export doesn’t honour. A dictionary is the reference that profiling and validation measure the data against.

Wide and long layouts

The same data can be laid out in more than one way. Suppose Lantern records the packs it sells of each coffee in each month. A wide layout gives each product a row and each month a column; a long layout gives each product–month combination its own row, with the month as a column of values.

Packs sold, wide layout (fictional)
productJanFebMar
House Blend 250g120135150
Ethiopia Yirgacheffe 250g807695
The same data, long layout
productmonthpacks
House Blend 250gJan120
House Blend 250gFeb135
House Blend 250gMar150
Ethiopia Yirgacheffe 250gJan80
Ethiopia Yirgacheffe 250gFeb76
Ethiopia Yirgacheffe 250gMar95

Both tables hold the same six numbers. A table is in wide format when the values of a variable, here the month, are spread across several columns, and in long format when that variable has a column of its own and each combination of values has its own row. Wickham (2014) avoids the terms as imprecise: they are relative, so a layout is only wider or longer than another layout of the same data.

Here the long layout is the tidy one, because month is a variable and so belongs in a column. Adding April adds two rows rather than a new column, and a chart or a model can use month directly. Wide layouts suit people reading a report, and some calculations that compare columns side by side. Converting between the two, called reshaping, is part of lesson 11.

Formulas

Average per unit

xˉunit=Sum of the values over all rowsNumber of distinct units\bar{x}_{\text{unit}} = \dfrac{\text{Sum of the values over all rows}}{\text{Number of distinct units}}
xˉunit\bar{x}_{\text{unit}}
The average per unit you are asking about: per order, per customer, per bookingunit of the values
Sum of the values over all rows\text{Sum of the values over all rows}
The column total, for example of line_totalunit of the values
Number of distinct units\text{Number of distinct units}
The number of distinct values of the unit’s identifier, such as distinct order_idunits

Assumes. The values can be added within a unit: they are ratio amounts such as dollars or packs.

Averaging the column directly gives the average per row, which equals the average per unit only when one row is one unit.

Primary key test

Distinct key values=nandRows with a blank key=0\text{Distinct key values} = n \quad \text{and} \quad \text{Rows with a blank key} = 0
nn
Number of rows in the tablerows
Distinct key values\text{Distinct key values}
Distinct values of the candidate key, or distinct combinations for a composite keyrows

Assumes. Blank means empty or null; placeholder codes such as “unknown” count as values and would also need checking.

Passing shows the key is unique in this file, not that a repeat can never arrive.

Worked examples

A first example: Classifying Harborview’s booking columns

Fictional figures

Harborview Hotel’s booking export includes the columns booking_id, check_in, nights, room_type, adults and rate (the price per night, in dollars). Classify each column by level of measurement and, for the numerical ones, as discrete or continuous. Which column should be the primary key?

  1. booking_id is a label for a booking. Adding or averaging booking numbers means nothing, so it is nominal, whatever characters it uses.
  2. check_in is a calendar date. Differences between dates are meaningful (check-out minus check-in is the length of stay), but ratios are not, because the calendar’s starting point is a convention: interval.
  3. nights and adults are counts with a true zero, so they are ratio and discrete: a 4-night stay is twice a 2-night stay, and no stay lasts 2.5 nights.
  4. rate is an amount of money with a true zero: ratio, treated as continuous in practice although it is recorded to the cent.
  5. room_type names a kind of room, such as Standard, Deluxe or Suite. The categories have no built-in order of measurement, so it is nominal; if an analysis ranks rooms by price, it is using the variable as ordinal and should say so.
  6. The key: one row is one booking, so the key must identify bookings. booking_id is the candidate; test it by checking that its distinct count equals the number of rows and that no row has it blank.

Answer. booking_id: nominal, and the primary key (if it passes the test). check_in: interval. nights and adults: ratio, discrete. rate: ratio, continuous in practice. room_type: nominal (ordinal only if you deliberately rank it).

What it means. The classification tells you which summaries mean something. Average nights and average rate are meaningful; the most common room type is the right summary for room_type; booking_id should only ever be counted or matched, never added up.

A harder example: The key and the unit in an airline’s ticket file

Fictional figures

Larkspur Regional Airways, a fictional airline, exports one row per flight coupon: one passenger on one flight segment of a booking. A return trip for two people is therefore four rows. The extract below covers three bookings. Find a primary key, the number of bookings and of passenger trips, and the average fare per coupon, per passenger trip and per booking.

Larkspur’s coupon file (fictional)
bookingpassengersegmentroutefare ($)
HX4111Harbour City → Eastmere120
HX4112Eastmere → Harbour City120
HX4121Harbour City → Eastmere120
HX4122Eastmere → Harbour City120
HX4211Eastmere → Ravensby150
HX4311Harbour City → Eastmere90
HX4312Eastmere → Ravensby110
  1. Name the unit: one row is one passenger on one segment of one booking. The key must identify exactly that, so expect it to need several columns.
  2. Test single columns. booking repeats (HX41 has four rows), passenger repeats (every booking has a passenger 1) and segment repeats. None is a key.
  3. Test pairs. booking + passenger repeats (HX41’s passenger 1 has two segments); booking + segment repeats (HX41’s segment 1 has two passengers); passenger + segment repeats (passenger 1, segment 1 appears in all three bookings).
  4. Test the triple. Every combination of booking, passenger and segment appears once in the seven rows, and none is blank, so booking + passenger + segment is a composite key. The passenger and segment numbers are labels within a booking, not amounts.
  5. Count the units. There are 3 distinct bookings; 4 distinct booking–passenger pairs (HX41-1, HX41-2, HX42-1, HX43-1), so 4 passenger trips; and 7 coupons. The fares add to 4×120+150+90+110=8304 \times 120 + 150 + 90 + 110 = 830 dollars.
  6. Average per unit (the formula above): per coupon 830÷7≈118.57830 \div 7 \approx 118.57; per passenger trip 830÷4=207.50830 \div 4 = 207.50; per booking 830÷3≈276.67830 \div 3 \approx 276.67.

Answer. Key: booking + passenger + segment. Average fare: $118.57 per coupon, $207.50 per passenger trip and $276.67 per booking.

What it means. All three averages are correct, and the largest is more than twice the smallest. A pricing analyst comparing Larkspur with a competitor’s one-way fares wants the coupon figure; a marketer studying what a customer spends on one purchase wants the booking figure. The question decides which is “the average fare”, and the key tells you which units the file can count.

Applied: a business decision: Which class size should Northfield publish?

Fictional figures

Northfield University is writing its prospectus. One small department runs three first-year modules with 10, 20 and 90 students, and its enrolment file has one row per student per module: 120 rows. The marketing team wants to quote an “average class size”. Which number should it publish?

  1. Unit: the module. Each module counts once: (10+20+90)÷3=40(10 + 20 + 90) \div 3 = 40 students.
  2. Unit: the enrolment, one row of the file. Each of the 10 students in the small module sits in a class of 10, each of the 20 in a class of 20, and each of the 90 in a class of 90. Averaging over the 120 rows gives (10×10+20×20+90×90)÷120=8,600÷120≈71.7(10 \times 10 + 20 \times 20 + 90 \times 90) \div 120 = 8{,}600 \div 120 \approx 71.7 students.
  3. Explain the gap. Averaging per module weights every module equally; averaging per enrolment weights each module by its size, so the large module counts 90 times. The two averages agree only when every module is the same size.
  4. Decide. Both figures honestly answer different questions. An applicant wants to know what their classes will be like, which is the per-enrolment figure. Publishing 40 alone would be accurate but would mislead that reader.

Answer. The average module has 40 students, but the average student sits in a class of about 72. Publish the per-student figure, or both figures with their definitions.

What it means. Changing the unit moves the headline from 40 to about 72 without any error in the data. Whenever an average is quoted, ask “average of what?”: per module or per student, per order or per customer.

Explore

Lantern’s full order export, in inspect-only mode: you can sort, scroll and read the column summaries, but not change anything. Use it to answer the three questions in the task, and keep a note of anything that doesn’t match the draft data dictionary above.

Loading the interactive…

Set the sizes of three modules and compare the average per module with the average class a student sits in. Make the three sizes equal, then make one much larger, and watch how far apart the two averages move.

Loading the interactive…

Common mistakes

  • “Counting rows counts orders.”

    Rows count units of observation. In the line-item report, seven rows described four orders, three customers and eight packs. Count distinct values of the identifier you mean (in SQL, COUNT(DISTINCT order_id) rather than COUNT(*)) and always say what a count is a count of.

  • “It’s a column of numbers, so it’s numerical.”

    Order numbers, customer numbers, postcodes and phone numbers are labels written with digits. Summing or averaging them produces numbers that mean nothing, and storing them as numbers destroys leading zeros. Ask whether adding two values would make sense; if not, the variable is categorical.

  • “If the values are numbers, any calculation is fine.”

    A rating of 4 is not twice a rating of 2, and 20 °C is not twice 10 °C. The level of measurement tells you which comparisons mean something: equality for nominal, order for ordinal, differences for interval, ratios for ratio. When you do average an ordinal variable, report its distribution as well.

  • “An email address makes a good key.”

    Emails change, are shared, are mistyped and are sometimes missing, so the same customer can end up with two “keys” and two customers with one. A key must be unique, never blank and stable; a system-issued identifier such as customer_id is.

  • “Long format is right and wide format is wrong.”

    Both can hold exactly the same information. The tidy layout is the one in which each variable has its own column, which depends on what the variables are. Wide tables are often the better layout for a report a person will read.

  • “The data dictionary describes the data as it is.”

    It describes what the data should be. The gaps between the two are the data’s quality problems, which is why you write the dictionary before trusting a file, and update it when the business changes a definition.

Guided practice

Work through these with hints when you need them. Every hint and every worked solution is there to be used.

Loading four questions…

On your own

No hints this time. Answer, check, and read the feedback; the solution appears once you have answered or if you ask for it. Your first answers count toward mastery.

Loading six questions…

In practice

Hotel revenue managers meet the unit-of-observation problem every week. A Harborview booking for three nights is one row in the booking file but three room-nights in the occupancy report, and the hotel’s performance figures, such as occupancy and the average rate per room-night, are counted in room-nights. An analyst who averages the rate column of the booking file weights a one-night stay the same as a fourteen-night stay, and gets a different number from the one the managers use. The fix is not cleverer arithmetic but the right unit: expand each booking into one row per night, or weight each booking’s rate by its nights.

Universities face the same choice when they publish class sizes, as the applied example showed, and retailers face it when they report “average basket size” per order, per visit or per customer. In each case the argument about which figure is right ends once someone names the unit.

Data dictionaries pay for themselves when data crosses a boundary between teams or systems. Suppose Lantern hires an agency to study why subscribers cancel. The agency will need to know what counts as an order, whether discount includes delivery charges, and whether a blank rating means “didn’t rate” or “rating lost”. Answering once, in writing, stops each analyst from guessing differently, and it gives everyone something to check the data against.

An analyst opening a new dataset therefore spends the first few minutes describing it, not analysing it:

  1. Say in one sentence what one row is.
  2. Find the key and test it: the distinct count against the row count, and the number of blanks.
  3. Classify each column’s kind and level, and note any column stored as the wrong type.
  4. Check that each observational unit has its own table, or note where facts are repeated.
  5. Start or update the data dictionary, marking every question you can’t yet answer.

None of this changes the data. It tells you what the data should be, so that the next step, profiling, can show where it isn’t.

Knowledge check

Six questions, one attempt each, no hints. Score 80% or more to complete the lesson; you can take it again at any time.

Loading six questions…

Summary

  • A dataset’s rows are observations (records) and its columns are variables (fields); a cell holds one value of one variable for one observation.
  • The unit of observation is what one row describes. Counts, totals and averages are per unit, so one question can have several correct answers: per line, per order, per customer.
  • Tidy data: each variable a column, each observation a row, each type of observational unit a table (Wickham, 2014). Business exports often break these rules for convenience.
  • Variables are categorical (nominal or ordinal) or numerical (discrete or continuous). Stevens’s levels say which comparisons are meaningful: equality, order, differences, ratios.
  • Identifiers are labels written with digits: compare and count them, never add or average them, and store them as text.
  • A primary key identifies each row: unique and never blank. A composite key uses two or more columns. Test a candidate by comparing its distinct count with the row count.
  • A data dictionary records each column’s meaning, level, type, unit and rules. It describes what the data should be; profiling finds where it isn’t.
  • Wide and long layouts can hold the same data; the tidy one gives each variable its own column.

Key formulas

Terms introduced

Dataset
A collection of values organised so that each value describes one characteristic of one thing; usually a table of rows and columns.
Observation
One row of a dataset: all the values recorded for one instance of the unit of observation. Also called a record.
Variable
One column of a dataset: a characteristic recorded for every observation. Also called a field or an attribute, and in machine learning a feature.
Unit of observation
The kind of thing one row describes, such as an order, an order line, a booking or a student.
Tidy data
A layout in which each variable forms a column, each observation forms a row and each type of observational unit forms a table (Wickham, 2014).
Nominal variable
A categorical variable whose categories have no natural order, such as region or product. Supports equality, counts and the mode.
Ordinal variable
A categorical variable whose categories have a meaningful order but no fixed distance between them, such as a 1–5 rating. Also supports the median and percentiles.
Interval variable
A numerical variable on which differences are meaningful but zero is an arbitrary point, so ratios are not, such as a calendar date or a temperature in °C.
Ratio variable
A numerical variable with a true zero meaning “none”, so differences and ratios are both meaningful, such as quantity, price or nights stayed.
Discrete variable
A numerical variable that takes separate values with gaps between them, usually a count, such as packs ordered.
Continuous variable
A numerical variable that can take any value within a range, at least in principle, usually a measurement such as weight or time.
Primary key
A column, or set of columns, whose values identify each row uniquely: no two rows share a value and none is blank.
Composite key
A primary key made of two or more columns, such as order_id and line together in a line-item report.
Data dictionary
A document recording, for each column of a dataset, its meaning, level of measurement, type, unit, allowed values, rule for blanks and business rules.
Wide format
A layout in which the values of one variable, such as the month, are spread across several columns.
Long format
A layout in which that variable has a column of its own and each combination of values has its own row.

Sources

  1. Wickham, H. (2014). Tidy Data. Journal of Statistical Software, 59(10). doi:10.18637/jss.v059.i10. jstatsoft.org/article/view/v059i10
  2. Stevens, S. S. (1946). On the theory of scales of measurement. Science, 103(2684), 677–680. doi.org/10.1126/science.103.2684.677
  3. Velleman, P. F. & Wilkinson, L. (1993). Nominal, ordinal, interval, and ratio typologies are misleading. The American Statistician, 47(1), 65–72.
  4. Illowsky, B. & Dean, S. (2023). Introductory Statistics 2e, sections 1.2 “Data, Sampling, and Variation in Data and Sampling” and 1.3 “Frequency, Frequency Tables, and Levels of Measurement”. OpenStax. openstax.org/books/introductory-statistics-2e/pages/1-3-freq…
  5. U.S. Geological Survey. “Data Dictionaries”. USGS Data Management. usgs.gov/data-management/data-dictionaries
  6. The PostgreSQL Global Development Group. PostgreSQL 18 Documentation, section 5.5, “Constraints”. postgresql.org/docs/current/ddl-constraints.html