r_d media
Что такое tidy data
Структурируем данные.
Дата-сайентисты говорят, что 80% времени тратят на подготовку данных, а на анализ — только 20%. Качественная информация позволяет построить эффективную модель и провести точные вычисления.
Рассказываем, в чем суть tidy data и как упростить структурирование данных.
Кто описал концепцию tidy data
Термин ввел дата-сайентист Хэдли Уикем в 2014 году.
Уикем — создатель нескольких десятков библиотек для языка R. В публикации для JSS (Journal of Statistical Software) он говорит, что tidy data (опрятные данные) — это стандартизированный способ соединить структуру набора данных и его семантику. Другими словами — физическое воплощение информации (например, в виде таблицы) и значения в наборе данных (числа, названия, номера, характеристики). Каждое значение определяется двумя параметрами — переменной и наблюдением. Переменная — это одна характеристика набора данных (например, возраст, город, профессия). Наблюдение — это группирование значений переменных по одному общему признаку. Например, информация об одном человеке.
В большинстве датасетов данные — в виде таблиц. Уикем называет три условия, при которых данные называют опрятными (tidy).
#1. Все переменные создают столбцы.
#2. Все наблюдения создают строчки.
#3. Каждый тип наблюдения создает одну таблицу.

Источник: Displayr
Если любое из условий нарушено, то данные считаются неопрятными (dirty data).
Большинство задач дата-аналитиков сосредоточены на массивах информации, операции с которыми требуют разных инструментов и команд. Иногда обработку данных осложняют аномалии БД:
Если формат данных правильный, аномалии не проявляются.
Использование инструментов, которые при обработке создают опрятные данные, сокращает время на рефакторинг БД. Его основная задача — упрощение работы c моделью без изменения функций. Обычно он необходим в работе с таблицами, в которых слишком большое количество строк или столбцов для баз конкретного типа либо содержится разнородная или несортированная информация. Большинство этих проблем устраняет tidy data.
Опрятные данные хорошо работают с R, потому что это векторный язык программирования. Информация в R сохраняется в виде кадров данных. Если ваши данные опрятны, показатели каждой переменной попадают в собственный вектор столбца.
Неструктурированные данные не выполняют одно или больше условий «опрятности». Уикем выделяет пять признаков беспорядочной информации:
Пример: в каталоге библиотеки информация о книге находится одновременно в таблицах «зарубежная литература» и «классика».
Пример: в одном файле содержится и список книг, и список посетителей.
Пример: в строках каталога, где содержится информация о названии книги, ошибочно указано издательство. Таким образом, сопоставляются две переменные, а не наблюдение и переменная.
Пример: в столбце «автор книги» также есть информация о годе печати.
Пример: в списке книг созданы столбцы «1997» и «1998», которые можно объединить в одну переменную — «год».
Tidy data что это
Мы будем говорить на одном языке, если вы прочитаете введение из статьи про Юнит-Экономику. Если в двух словах, то все маркетинговые коммуникации можно разделить на перфоманс и бренд-коммуникации. Перфоманс механики — это рекламные кампании, направленные непосредственно на повышение продаж. Обычно такие коммуникации содержат оффер (скидка, специальные условия, предложение купить конкретный товар). Бренд-коммуникации помогают формировать узнаваемость и имидж бренда, повышают конверсию перфоманс маркетинга и приводят к продажам через прямые заходы. Однако точно оценить вклад таких коммуникаций в продажи трудно. Оптимальная пропорция бюджета зависит от размера компании и длительности цикла выбора и покупки.
Глоссарий:
Атрибуция — это процесс мэтчинга прибыли от клиента с затратами на рекламные источники, которые привели к привлечению этого клиента. Один и тот же клиент мог взаимодействовать с разными рекламными каналами. За каждое такое взаимодействие заплатил рекламодатель. Модель атрибуции поможет распределить прибыль от этого клиента по всем каналам с которыми он взаимодействовал.
При модели атрибуции «по последнему клику» вся прибыль от клиента относится к тому каналу, который был последним перед покупкой. В «линейной модели» прибыль от клиента равномерно распределится по всем каналам. Существует множество других моделей.
В этой статье все методы оценки инкрементального разделены на три группы: количественный анализ продаж; user-base методы и социологический подход (опросы).
Но в реальной жизни флуктуация кривой выручки / продаж гораздо сильней. Её определяют внешние факторы. В первую очередь сезонность. Можно попробовать учесть сезонную компоненту, чтобы уточнить эффект от рекламы путем сравнения ожидаемой и фактической кривых продаж.
Если существует зависимость между рекламным бюджетом и уровнем продаж, то линейная модель её заметит и вернёт коэффициент. Этот коэффициент будет отражать цену привлечения клиента через охватную кампанию. Интерпретировать такие модели нужно с осторожностью. Во-первых нужно убедиться, что p-value при этом коэффициенте ниже 0.05. Это будет означать что реклама стат. значимо влияет на продажи.
Во-вторых нужно рассчитать R² который покажет, какую долю вариации выручки\продаж можно объяснить факторами, которые вы включили в модель. Если показатель будет низким (точных границ нет, но скажем менее 0.3), значит существуют другие неучтенные факторы, которые в значительной мере объясняют продажи.
В основе подхода классическая механика АБ-теста: просто сравнить между собой группу на которую оказывали воздействие с контрольной группой, где воздействия не было. Так делает Авито и Юлмарт, которые могут позволить себе купить рекламу на телеке в регионах 1,3,5 и не покупать в 2,4,6, а потом сравнить бизнес-метрики между этими группами регионов.
Для ребят по-скромнее тоже есть опции: можно таргетировать ютуб-кампанию только на женщин и сравнить кривые продаж по полу в период рекламной кампании. Если у вас большая клиентская база и вы запускаете кампании по удержанию/возврату, то в аудиторию ремаркетинга можно выделить 80% базы, а 20% клиентов не показывать рекламу, а потом сравнить между собой сегменты на который воздействовала реклама и органический возврат.
10 Продвинутый tidyverse
10.1 Объединение нескольких датафреймов
10.1.1 Соединение структурно схожих датафреймов: bind_rows(), bind_cols()
Функции bind_rows() и bind_cols() могут работать не только с двумя, но сразу с несколькими датафреймами.
На входе в функции bind_rows() и bind_cold() можно подавать как сами датафреймы или тибблы через запятую, так и список из датафреймов/тибблов.
10.1.2 Реляционные данные: *_join()
В случае с реляционными данными простых bind_rows() и bind_cols() становится недостаточно.
Давайте попробуем посоединять band_members и band_instruments разными вариантами *_join() и посмотрим, что у нас получится. Все эти функции имеют на входе два обязательных аргумента ( x = и y = ) в которые мы должны подставить два датафрейма/тиббла которые мы хотим объединить. Главное различие между этими функциями заключается в том, что они будут делать, если уникальные значения в ключах x и y не соответствуют друг другу.
Часто случается, что колонки-ключи называются по-разному в двух тибблах. Их необязательно переименовывать, можно поставить соответстие вручную используя проименованный вектор:
На самом деле, оба варианта приемлимы, оба варианта возможны в реальных данных, а разные функции и статистические пакеты могут требовать от вас как длинный, так и широкий форматы.
Таким образом, нам нужно научиться переводить из широкого формата в длинный и наоборот.
tidyr::pivot_longer() : из широкого в длинный формат
tidyr::pivot_wider() : из длинного в широкий формат
What is tidy data?
Summary: The principles of Hadley Wickham’s tidy data, and how it relates to long and wide form data.
Tidy data¶
In wide form, we might list out the sales for each quarter:
| Store_Id | Year | Q1_Sales | Q2_Sales | Q3_Sales | Q4_Sales |
|---|---|---|---|---|---|
| A001 | 2018 | 55 M | 45 M | 22 M | 50 M |
| A002 | 2018 | 98 M | 70 M | 60 M | 60 M |
In long form, we would not use the column to label the quarter. Instead, we would add a separate column for the quarter, like so:
| Store_Id | Year | Quarter | Sales |
|---|---|---|---|
| A001 | 2018 | 1 | 55 M |
| A001 | 2018 | 2 | 45 M |
| A001 | 2018 | 3 | 22 M |
| A001 | 2018 | 4 | 50 M |
| A002 | 2018 | 1 | 55 M |
| . | . | . | . |
In the long vs wide post, we concentrated on how to convert from one format to the other. This post will concentrate on when we would want to put the data into «tidy» format, and why.
Tidy format¶
Hadley Wickham defines «tidy data» is data stored in «3rd normal form». Restated in language used by statisticans and data scienctists, we have:
Looking at the long and wide forms of our sales data, it can be difficult to apply these rules to say which one is «tidy». For example, if we are trying to observe quarterly sales, the long form would be tidy. If we are trying to observe annual sales, there is an argument that the wide form with all the data about a year in a single row, is tidy.
An easier way for me to think about whether a dataset is «tidy» or not is to consider the multiple ways a dataset might become untidy. From Wickham’s paper, these are
Other examples¶
Medical data: age, weight, and gender¶
| name | age | weight | gender |
|---|---|---|---|
| Alice | 34 | 115lb | Female |
| Bob | 35 | 160lb | Male |
| Christine | 38 | 125 lb | Female |
The same data can be presented in a long format:
| name | variable | value |
|---|---|---|
| Alice | age | 34 |
| Alice | gender | Female |
| Alice | weight | 115lb |
| Bob | age | 35 |
| Bob | weight | 160lb |
| Bob | gender | Male |
| . | . | . |
Tidy version: the wide dataset.
Medical trial data¶
Let’s take a dataset from the Wikipedia page on Simpson’s paradox which looks at the effect of two different treatments for kidney stones. Here is the original dataset:
Here are two contenders for a «tidy» format. In both cases, it is easy to note that the columns have two pieces of information: the treatment and the outcome. Let’s separate these out:
| Stone size | Treatment | Recovered | Failed |
|---|---|---|---|
| Small | A | 81 | 6 |
| Small | B | 234 | 36 |
| Large | A | 192 | 71 |
| Large | B | 55 | 25 |
The question is whether the outcome should be a separate column or not. An alternative is:
| Stone size | Treatment | Outcome | Count |
|---|---|---|---|
| Small | A | Recovered | 81 |
| Small | A | Failed | 6 |
| Small | B | Recovered | 234 |
| Small | B | Failed | 36 |
| Large | A | Recovered | 192 |
| Large | A | Failed | 71 |
| Large | B | Recovered | 55 |
| Large | B | Failed | 25 |
Box office revenue¶
We can go to BoxOffice Mojo and get information on ticket sales for the first 6 weeks (rounded to the nearest million)
| Movie | Release date | Wk1 | Wk2 | Wk3 | Wk4 | Wk5 | Wk6 |
|---|---|---|---|---|---|---|---|
| The Lego Movie | 2014-02-07 | 80M | 71M | 37M | 26M | 15M | 10M |
| Big Hero 6 | 2014-11-07 | 76M | 40M | 33M | 21M | 10M | 8M |
| Incredibles 2 | 2018-06-15 | 269M | 125M | 81M | 44M | 26M | 20M |
In this case, the «tidy» data set would take the form
| Movie | Date | Week | Revenue |
|---|---|---|---|
| The Lego Movie | 2014-02-07 | 1 | 80M |
| The Lego Movie | 2014-02-14 | 2 | 71M |
| The Lego Movie | 2014-02-21 | 3 | 37M |
| . | . | . | . |
There is even a case for saying that «Date» and «Week» contain overlapping information, and that a better way of approaching the problem might be to separate off the movie’s opening date into a separate dataframe, and keep only the «Date» or «Week» column in this dataframe.
This case is interesting, because even though the form above is the «tidy» form, it might not be the form we want our data in. For example, we could try and build a model that takes the last two weeks of the box office revenue and uses it to predict the current week’s revenue. For sklearn to be able to model this, we would need to included the previous two weeks as «features» in our dataframe, so we would try and make our dataframe look like the following:
| Movie | Date | Week | Revenue_lag2 | Revenue_lag1 | Revenue (target) |
|---|---|---|---|---|---|
| The Lego Movie | 2014-02-07 | 1 | NaN | NaN | 80M |
| The Lego Movie | 2014-02-14 | 2 | NaN | 80M | 71M |
| The Lego Movie | 2014-02-21 | 3 | 80M | 71M | 37M |
| The Lego Movie | 2014-02-21 | 4 | 71M | 37M | 26M |
| . | . | . | . |
This is the form we would need for our model, even though it isn’t «tidy».
When to be tidy?¶
Hadley Wickham works as one of the primary developers of R, and has constructed the «TidyVerse» set of functions. These are functions that are designed to take in tidy data, and if they output a dataframe, the output should also be tidy. The output could also be graphs. So the R approach to the problem of «we need to include lags» is to write the machine learning code so that it can take a tidy dataframe and do the lagging for you. Python has something similar with statsmodels and the timeseries packages contained within.
Even if working in Python, we will not manage to get the level of consistence that the Tidyverse provides R users, it is still useful to have a standardized format, even if we choose not to use it. Knowing about the TidyVerse gives us a set of best practices, and we break them only out of the practical needs of our models.
As Wickham acknowledges at the end of the paper, a «tidy» or «standard» data format is useful only so far as it makes future analysis less painful. It should not be considered an end onto itself. The current «tidy» format isn’t even necessarily the best one, but simply one that we have converged on as a community.
Damien martin
I am a data scientist with an interest in what drives the world. Background in Physics, Math, and Computer Science. Interested in Algorithms, Games, Books, Music, and Martial Arts. That is, when I am not off taking pictures somewhere!
Name to Age
How much does your name say about your age? We use the database of names from the.
Munging with MultiIndices: election data
We show how to take an Excel spreadsheet, with merged column headings, and process it.
Tidy data
(This is an informal and code heavy version of the full tidy data paper. Please refer to that for more details.)
Data tidying
It is often said that 80% of data analysis is spent on the cleaning and preparing data. And it’s not just a first step, but it must be repeated many times over the course of analysis as new problems come to light or new data is collected. To get a handle on the problem, this paper focuses on a small, but important, aspect of data cleaning that I call data tidying: structuring datasets to facilitate analysis.
The principles of tidy data provide a standard way to organise data values within a dataset. A standard makes initial data cleaning easier because you don’t need to start from scratch and reinvent the wheel every time. The tidy data standard has been designed to facilitate initial exploration and analysis of the data, and to simplify the development of data analysis tools that work well together. Current tools often require translation. You have to spend time munging the output from one tool so you can input it into another. Tidy datasets and tidy tools work hand in hand to make data analysis easier, allowing you to focus on the interesting domain problem, not on the uninteresting logistics of data.
Defining tidy data
Happy families are all alike; every unhappy family is unhappy in its own way — Leo Tolstoy
Like families, tidy datasets are all alike but every messy dataset is messy in its own way. Tidy datasets provide a standardized way to link the structure of a dataset (its physical layout) with its semantics (its meaning). In this section, I’ll provide some standard vocabulary for describing the structure and semantics of a dataset, and then use those definitions to define tidy data.
Data structure
Most statistical datasets are data frames made up of rows and columns. The columns are almost always labeled and the rows are sometimes labeled. The following code provides some data about an imaginary classroom in a format commonly seen in the wild. The table has three columns and four rows, and both rows and columns are labeled.
There are many ways to structure the same underlying data. The following table shows the same data as above, but the rows and columns have been transposed.
The data is the same, but the layout is different. Our vocabulary of rows and columns is simply not rich enough to describe why the two tables represent the same data. In addition to appearance, we need a way to describe the underlying semantics, or meaning, of the values displayed in the table.
Data semantics
A dataset is a collection of values, usually either numbers (if quantitative) or strings (if qualitative). Values are organised in two ways. Every value belongs to a variable and an observation. A variable contains all values that measure the same underlying attribute (like height, temperature, duration) across units. An observation contains all values measured on the same unit (like a person, or a day, or a race) across attributes.
A tidy version of the classroom data looks like this: (you’ll learn how the functions work a little later)
This makes the values, variables, and observations more clear. The dataset contains 36 values representing three variables and 12 observations. The variables are:
The tidy data frame explicitly tells us the definition of an observation. In this classroom, every combination of name and assessment is a single measured observation. The dataset also informs us of missing values, which can and do have meaning. Billy was absent for the first quiz, but tried to salvage his grade. Suzy failed the first quiz, so she decided to drop the class. To calculate Billy’s final grade, we might replace this missing value with an F (or he might get a second chance to take the quiz). However, if we want to know the class average for Test 1, dropping Suzy’s structural missing value would be more appropriate than imputing a new value.
Variables may change over the course of analysis. Often the variables in the raw data are very fine grained, and may add extra modelling complexity for little explanatory gain. For example, many surveys ask variations on the same question to better get at an underlying trait. In early stages of analysis, variables correspond to questions. In later stages, you change focus to traits, computed by averaging together multiple questions. This considerably simplifies analysis because you don’t need a hierarchical model, and you can often pretend that the data is continuous, not discrete.
Tidy data
Tidy data is a standard way of mapping the meaning of a dataset to its structure. A dataset is messy or tidy depending on how rows, columns and tables are matched up with observations, variables and types. In tidy data:
Every column is a variable.
Every row is an observation.
Every cell is a single value.
This is Codd’s 3rd normal form, but with the constraints framed in statistical language, and the focus put on a single dataset rather than the many connected datasets common in relational databases. Messy data is any other arrangement of the data.
Tidy data makes it easy for an analyst or a computer to extract needed variables because it provides a standard way of structuring a dataset. Compare the different versions of the classroom data: in the messy version you need to use different strategies to extract different variables. This slows analysis and invites errors. If you consider how many data analysis operations involve all of the values in a variable (every aggregation function), you can see how important it is to extract these values in a simple, standard way. Tidy data is particularly well suited for vectorised programming languages like R, because the layout ensures that values of different variables from the same observation are always paired.
While the order of variables and observations does not affect analysis, a good ordering makes it easier to scan the raw values. One way of organising variables is by their role in the analysis: are values fixed by the design of the data collection, or are they measured during the course of the experiment? Fixed variables describe the experimental design and are known in advance. Computer scientists often call fixed variables dimensions, and statisticians usually denote them with subscripts on random variables. Measured variables are what we actually measure in the study. Fixed variables should come first, followed by measured variables, each ordered so that related variables are contiguous. Rows can then be ordered by the first variable, breaking ties with the second and subsequent (fixed) variables. This is the convention adopted by all tabular displays in this paper.
Tidying messy datasets
Real datasets can, and often do, violate the three precepts of tidy data in almost every way imaginable. While occasionally you do get a dataset that you can start analysing immediately, this is the exception, not the rule. This section describes the five most common problems with messy datasets, along with their remedies:
Column headers are values, not variable names.
Multiple variables are stored in one column.
Variables are stored in both rows and columns.
Multiple types of observational units are stored in the same table.
A single observational unit is stored in multiple tables.
Surprisingly, most messy datasets, including types of messiness not explicitly described above, can be tidied with a small set of tools: pivoting (longer and wider) and separating. The following sections illustrate each problem with a real dataset that I have encountered, and show how to tidy them.
Column headers are values, not variable names
A common type of messy dataset is tabular data designed for presentation, where variables form both the rows and columns, and column headers are values, not variable names. While I would call this arrangement messy, in some cases it can be extremely useful. It provides efficient storage for completely crossed designs, and it can lead to extremely efficient computation if desired operations can be expressed as matrix operations.
The following code shows a subset of a typical dataset of this form. This dataset explores the relationship between income and religion in the US. It comes from a report produced by the Pew Research Center, an American think-tank that collects data on attitudes to topics ranging from religion to the internet, and produces many reports that contain datasets in this format.
Here we use values_drop_na = TRUE to drop any missing values from the rank column. In this data, missing values represent weeks that the song wasn’t in the charts, so can be safely dropped.
In this case it’s also nice to do a little cleaning, converting the week variable to a number, and figuring out the date corresponding to each week on the charts:
Finally, it’s always a good idea to sort the data. We could do it by artist, track and week:
Or by date and rank:
Multiple variables stored in one column
First we use pivot_longer() to gather up the non-variable columns:
Storing the values in this form resolves a problem in the original data. We want to compare rates, not counts, which means we need to know the population. In the original format, there is no easy way to add a population variable. It has to be stored in a separate table, which makes it hard to correctly match populations to counts. In tidy form, adding variables for population and rate is easy because they’re just additional columns.
In this case, we could also do the transformation in a single step by supplying multiple column names to names_to and also supplying a grouped regular expression to names_pattern :
Variables are stored in both rows and columns
The most complicated form of messy data occurs when variables are stored in both rows and columns. The code below loads daily weather data from the Global Historical Climatology Network for one weather station (MX17004) in Mexico for five months in 2010.
To tidy this dataset we first use pivot_longer to gather the day columns:
For presentation, I’ve dropped the missing values, making them implicit rather than explicit. This is ok because we know how many days are in each month and can easily reconstruct the explicit missing values.
We’ll also do a little cleaning:
This form is tidy: there’s one variable in each column, and each row represents one day.
Multiple types in one table
Datasets often involve values collected at multiple levels, on different types of observational units. During tidying, each type of observational unit should be stored in its own table. This is closely related to the idea of database normalisation, where each fact is expressed in only one place. It’s important because otherwise inconsistencies can arise.
The billboard dataset actually contains observations on two types of observational units: the song and its rank in each week. This manifests itself through the duplication of facts about the song: artist is repeated many times.
Then use that to make a rank dataset by replacing repeated song facts with a pointer to song details (a unique song id):
You could also imagine a week dataset which would record background information about the week, maybe the total number of songs sold or similar “demographic” information.
Normalisation is useful for tidying and eliminating inconsistencies. However, there are few data analysis tools that work directly with relational data, so analysis usually also requires denormalisation or the merging the datasets back into one table.
One type in multiple tables
It’s also common to find data values about a single type of observational unit spread out over multiple tables or files. These tables and files are often split up by another variable, so that each represents a single year, person, or location. As long as the format for individual records is consistent, this is an easy problem to fix:
Read the files into a list of tables.
For each table, add a new column that records the original file name (the file name is often the value of an important variable).
Combine all tables into a single table.







