Skip to main content

Session 1. The working environment and pandas I: one table

Preview of the notebook. To run it, download the session or open it in Colab.

Download session (zip) Open in Colab (R) All sessions

# Only for Google Colab. On your own computer this cell does nothing: run it and go on.
# In Colab: run it first, in every new session. It downloads the data and prints "Ready".
if (nzchar(Sys.getenv("COLAB_RELEASE_TAG")) || dir.exists("/content/sample_data")) {
  setwd("/content")
  if (!dir.exists("DMA/S01_pandas_I")) {
    download.file("https://albarran.github.io/DMA/sessions/S01_pandas_I.zip", "S01_pandas_I.zip", mode = "wb", quiet = TRUE)
    unzip("S01_pandas_I.zip")
  }
  need <- setdiff(c("tidyverse"), rownames(installed.packages()))
  if (length(need) > 0) install.packages(need)
  setwd("DMA/S01_pandas_I")
  cat("Ready. Working directory:", getwd(), "\n")
}

The R version of Session 1: the blocks The same in R of S01_pandas_I.ipynb as cells you can run, in the same order and with the same numbers. The concepts are explained in the main notebook; here each block recalls the rule in one line and applies it. Use this notebook if you work in R, or to check an R block of the main notebook by running it. The exercises of §12 are the same: do them in one of the two notebooks.

Two styles of R appear, and you will read both in other people’s code:

This notebook needs the kernel R (DMA) (top right in Jupyter). If it is missing, see Setup on the course site.

1. The environment

The kernel of this notebook is R. The rules are those of the main notebook: cells run in the order you run them; Kernel → Restart Kernel and Run All Cells before you trust a result; relative paths from the working directory.

R.version.string
basename(getwd())                       # the working directory: the folder of the notebook
file.exists("data/wdi_panel.csv")

2. The objects: vector, data.frame, tibble

Rule: a table is a set of columns of the same length; each column has one type.

In R these objects are part of the language. A vector is a sequence of values of one type (the pandas Series). A data.frame is a list of vectors of the same length (the pandas DataFrame); its row names play the part of the pandas index.

# base R
unemp <- c(ESP = 12.2, FRA = 7.3, DEU = 3.1)                 # a named vector
unemp["ESP"]
mean(unemp)
small <- data.frame(country      = c("Spain", "France", "Germany"),
                    unemployment = c(12.2, 7.3, 3.1),
                    population_m = c(48.4, 68.4, 83.3),
                    row.names    = c("ESP", "FRA", "DEU"))
small$unemployment                                           # one column: a vector
small["ESP", "unemployment"]                                 # by row name and column name
small[1, 2]                                                  # by position (R counts from 1)
small
str(small)                   # one type per column

The tidyverse table is the tibble: a data.frame that prints only what fits on the screen, shows the type of each column and has no row names.

# tidyverse
library(tidyverse)
small_tbl <- tibble(country      = c("Spain", "France", "Germany"),
                    unemployment = c(12.2, 7.3, 3.1),
                    population_m = c(48.4, 68.4, 83.3))
small_tbl

Importing the data. read.csv() (base R) returns a data.frame; read_csv() (package readr) returns a tibble. In text columns read.csv() reads an empty cell as the empty text "", so we tell it that empty means missing.

# importing the file
wdi_df <- read.csv("data/wdi_panel.csv", na.strings = "")          # base R: a data.frame
wdi    <- read_csv("data/wdi_panel.csv", show_col_types = FALSE)   # tidyverse: a tibble
class(wdi_df)
class(wdi)

A tibble is a data.frame, so base R syntax works on it: from here on the cells use wdi, the tibble (and wdi_df only where base R prints better).

3. Tidy data and the unit of observation

Rule: before computing anything, state the unit of observation and check the key.

Question. What does one row of the WDI file describe?

head(wdi)
# base R
dim(wdi)                                         # rows, columns
anyDuplicated(wdi[, c("iso3", "year")])          # 0: no duplicates
# tidyverse
wdi |> count(iso3, year) |> filter(n > 1)        # 0 rows: no duplicates
n_distinct(wdi$iso3)
n_distinct(wdi$year)

One row is a country in a year: a panel with key (iso3, year), 266 codes × 24 years = 6,384 rows.

4. Types of variables

Rule: the type of a variable decides which operations make sense. Stocks and flows add across units; rates and ratios need weights.

str(wdi_df)          # base R
glimpse(wdi)         # tidyverse
colSums(is.na(wdi))  # missing values per column

chr is text and dbl is a number with decimals. Only population (a stock) can be added across countries.

5. Select columns and filter rows

Rule: write the condition in words first, and count the rows before and after. The filter defines the sample.

Question. Which countries had unemployment above 15% in 2023?

Base R: df[rows, columns]. The condition is NA where unemployment is missing in 2023. With df[cond, ], base R returns one row full of NA for each of them. which(cond) keeps the rows where the condition is TRUE; subset() does the same.

# base R: df[rows, columns]
cond <- wdi$year == 2023 & wdi$unemployment > 15
table(cond, useNA = "ifany")                # FALSE, TRUE and missing (NA)
nrow(wdi[cond, ])                           # 49: the 15 rows, and one row of NA for each missing condition
nrow(wdi[which(cond), ])                    # 15
wdi[which(cond), c("country", "region", "unemployment")]
subset(wdi, year == 2023 & unemployment > 15, select = c(country, region, unemployment))

Tidyverse: filter() for rows (it drops the rows where the condition is missing), select() for columns.

# tidyverse
high <- wdi |>
  filter(year == 2023, unemployment > 15) |>
  select(country, region, unemployment)
high
count(high, region, sort = TRUE)            # how many of the 15 in each region

15 countries, most of them in Sub-Saharan Africa (8) and in the Middle East and North Africa (6). Limit: ILO modelled estimates, and 34 of the 266 rows of 2023 have no value.

Question. How many countries does the file have? (The United Nations has 193 member states.)

# base R
length(unique(wdi$country))
countries  <- wdi[!is.na(wdi$region), ]
aggregates <- wdi[is.na(wdi$region), ]
wdi |> filter(is.na(region)) |> distinct(country) |> head(12)
# tidyverse
n_distinct(wdi$country)
countries  <- wdi |> filter(!is.na(region))
aggregates <- wdi |> filter(is.na(region))
n_distinct(countries$iso3)
n_distinct(aggregates$iso3)

217 countries and territories and 49 aggregates (World, Euro area, High income, …). From here on the sample is countries.

6. Create variables

Rule: a new variable is a function of other columns, computed row by row. Say its units aloud.

Question. The file has GDP per capita. How large is each economy?

The base R cell and the tidyverse cell create the same three columns: run both, or one of them.

# base R
countries$gdp_bn      <- countries$gdp_pc_ppp * countries$population / 1e9
countries$log_gdp_pc  <- log(countries$gdp_pc_ppp)
countries$high_income <- as.integer(countries$income_group == "High income")
# tidyverse
countries <- countries |>
  mutate(gdp_bn      = gdp_pc_ppp * population / 1e9,          # billions of PPP $
         log_gdp_pc  = log(gdp_pc_ppp),
         high_income = as.integer(income_group == "High income"))

c23 <- countries |> filter(year == 2023)                       # the cross-section of 2023
c23 |>
  filter(iso3 %in% c("CHN", "IND", "USA", "ESP", "LUX")) |>
  select(country, population, gdp_pc_ppp, gdp_bn, log_gdp_pc, high_income)

China is the largest of the five economies with less than a third of the GDP per capita of the United States; Luxembourg has the highest GDP per capita and a small economy. Limit: PPP dollars compare volumes; at market exchange rates the United States is larger.

A missing input gives a missing result in arithmetic, and in R also in a comparison: the dummy of the 33 countries without an unemployment rate is NA. pandas gives them a 0 and Stata a 1.

# a dummy from a condition with missing values: R keeps them missing
table(as.integer(c23$unemployment > 15), useNA = "ifany")

7. Sort

Rule: say which variable defines “first” before sorting.

Question. Which are the largest economies in 2023? Is it the same list as the richest?

# base R
top <- c23[order(-c23$gdp_bn), c("country", "gdp_bn", "gdp_pc_ppp")]
head(top, 8)
# tidyverse
c23 |>
  arrange(desc(gdp_bn)) |>
  select(country, gdp_bn, gdp_pc_ppp) |>
  head(8)
c23 |>
  arrange(desc(gdp_pc_ppp)) |>
  select(country, gdp_bn, gdp_pc_ppp) |>
  head(8)

Two lists with no country in common. Limit: in Singapore, Luxembourg, Ireland, Qatar, Macao and Bermuda GDP per capita overstates the income of residents; GNI per capita is the better measure.

Question (if time; otherwise at home). The ten highest inflation rates in the panel. Are they errors?

countries |>
  arrange(desc(inflation)) |>
  select(country, year, inflation) |>
  head(10)
countries |>
  filter(iso3 == "ZWE", between(year, 2005, 2010)) |>
  select(country, year, inflation)

The ten are documented episodes. Limit: Zimbabwe has no value from 2005 to 2009, when its inflation was highest.

8. Summarise

Rule: next to every mean or median, report how many observations it is based on.

Question. What is the GDP per capita of the typical country in 2023?

R returns NA for a summary of a column with missing values until you write na.rm = TRUE.

# base R
summary(c23$gdp_pc_ppp)                 # the last figure counts the missing values
mean(c23$gdp_pc_ppp)                    # NA: there are missing values
mean(c23$gdp_pc_ppp, na.rm = TRUE)
# tidyverse
c23 |>
  summarise(n      = n(),
            n_gdp  = sum(!is.na(gdp_pc_ppp)),
            mean   = mean(gdp_pc_ppp, na.rm = TRUE),
            median = median(gdp_pc_ppp, na.rm = TRUE))

The typical country: about 17,700 PPP dollars (the median); the mean is 27,400. Limit: 197 of the 217 countries have data.

9. Group, and who is missing

Rule: one row per group, always with its count. For missing values: count, explain, then decide.

Question. How does income vary across regions in 2023, and how many countries is each figure based on?

# base R (the formula drops the rows with missing values)
aggregate(gdp_pc_ppp ~ region, data = c23, FUN = median)
# tidyverse
c23 |>
  group_by(region) |>
  summarise(n_countries   = n(),                        # all rows: COUNT(*) in SQL; count() gives the same
            n_with_gdp    = sum(!is.na(gdp_pc_ppp)),    # rows with a value: COUNT(gdp_pc_ppp) in SQL
            gdp_pc_median = median(gdp_pc_ppp, na.rm = TRUE)) |>
  arrange(gdp_pc_median)

A factor of 11 between the median country of Sub-Saharan Africa and that of Europe and Central Asia. Limit: North America rests on 3 economies and South Asia on 6.

Question (if time; otherwise at home). Which countries never report an unemployment rate? Are they a random subset?

# base R
years_with_u <- tapply(!is.na(countries$unemployment), countries$country, sum)
names(years_with_u[years_with_u == 0])
# tidyverse
never <- countries |>
  group_by(country) |>
  summarise(years_with_u = sum(!is.na(unemployment))) |>
  filter(years_with_u == 0)
nrow(never)

30 small territories and microstates, plus Kosovo: missing at random given size (MAR), far from a random sample of the world.

10. Averages and weights

Rule: for every average of a ratio, say what the weights are.

Question. What is “the GDP per capita of Sub-Saharan Africa”? The average country (mean of ratios) or the average person (ratio of sums, a mean weighted by population)?

# base R: weighted.mean(x, w)
ok <- c23[!is.na(c23$gdp_pc_ppp) & !is.na(c23$population), ]
sapply(split(ok, ok$region), function(d) weighted.mean(d$gdp_pc_ppp, d$population))
# tidyverse
reg <- c23 |>
  filter(!is.na(gdp_pc_ppp), !is.na(population)) |>
  group_by(region) |>
  summarise(mean_of_ratios = mean(gdp_pc_ppp),
            ratio_of_sums  = sum(gdp_pc_ppp * population) / sum(population))
reg

Check against the source (if time; otherwise at home). The regional aggregates of the World Bank are rows of aggregates.

agg_codes <- c("East Asia & Pacific" = "EAS", "Europe & Central Asia" = "ECS",
               "Latin America & Caribbean" = "LCN", "Middle East & North Africa" = "MEA",
               "North America" = "NAC", "South Asia" = "SAS", "Sub-Saharan Africa" = "SSF")
a23 <- aggregates |> filter(year == 2023)

reg |>
  mutate(official = a23$gdp_pc_ppp[match(agg_codes[region], a23$iso3)]) |>
  select(region, ratio_of_sums, official)
c23 |>
  filter(region == "Middle East & North Africa", is.na(gdp_pc_ppp)) |>
  select(country, population)

About 4,800 PPP dollars for the average person of Sub-Saharan Africa and 6,200 for the average country. Limit: who is missing changes the answer (Syria and Yemen in the Middle East and North Africa).

11. Describe, predict, explain

Rule: say which of the three your sentence claims.

Question. Do people in richer countries live longer?

cut() creates a category from a numeric variable; with the quartiles as breaks it gives four groups with the same number of countries.

# base R: cut() with the quartiles as breaks
breaks <- quantile(c23$gdp_pc_ppp, 0:4 / 4, na.rm = TRUE)
c23$income_bracket <- cut(c23$gdp_pc_ppp, breaks, include.lowest = TRUE,
                          labels = c("Q1 poorest", "Q2", "Q3", "Q4 richest"))
# tidyverse (uses the column created above)
c23 |>
  filter(!is.na(income_bracket)) |>
  group_by(income_bracket) |>
  summarise(count = n(), median = median(life_exp), min = min(life_exp), max = max(life_exp))

The table describes (16 more years of median life expectancy in the richest quartile) and predicts with a wide margin (the ranges overlap). Limit: it does not explain.

12. Exercise

In class: 12.1, and 12.2 if there is time. At home: the rest.

Work in pairs. Before writing code, tell your partner the unit of observation and what the result should look like (one number? a table with how many rows?). Finish each one with a sentence and its limit. Use R here, in base R or with the tidyverse, or pandas in S01_pandas_I.ipynb: one language is enough.

12.1 (in class) How many countries have a value of gdp_pc_ppp in 2000, and how many in 2023? Which countries are in one year and absent from the other, and why might that be? Use countries. Useful in R: filter(), !is.na(), pull(), setdiff(a, b).

# your code here

12.2 (if time; otherwise at home) Spain against the euro area: the unemployment rate from 2007 to 2014. The euro area is an aggregate (iso3 equal to EMU), so start from wdi. Build a table with the columns country, year and unemployment, sorted by year. Read the gap between the two in 2007 and in 2013 and write one sentence: was Spain’s crisis exceptional?

# your code here

12.3 (at home) The ten countries with the highest unemployment in 2023, with their region and income group. What do they have in common?

# your code here

12.4 (at home) Life expectancy in 2019 in high-income countries and in the rest: the average country and the average person. Which one would a health ministry use, and which one a demographer comparing health systems?

# your code here

The table of equivalences (pandas, base R, dplyr, Stata, SQL) is at the end of the main notebook.

Read: Wickham, Çetinkaya-Rundel and Grolemund, R for Data Science, 2nd ed., chapters Data transformation and Data tidying (r4ds.hadley.nz).