Life expectancy for a country is the mean length of life over people of a country. Using variables life expectancy and population of a country:

  1. derive a formula to compute life expectancy of a continent (a group of countries)
  2. plot how life expectancy changed over time for each continent
  3. do the same for the whole planet

Given a set \(S = X \cup Y\), with \(X = \{x_1, \ldots, x_{n_x}\}\) and \(Y = \{y_1, \ldots, y_{n_y}\}\), we can compute the mean of \(S\) \[\mu = \frac{\sum_i x_i + \sum_i y_i}{n_x + n_y}\] using only the means and sizes of \(X\) and \(Y\) as the weigthed mean of the means of \(X\) and \(Y\):

\[\mu = \frac{\frac{\sum_i x_i}{n_x} \cdot n_x + \frac{\sum_i y_i}{n_y} \cdot n_y}{n_x + n_y}\]

library(dplyr)
library(ggplot2)
library(gapminder)
gapminder_continent = 
  gapminder %>% 
  mutate(lifeExpXpop = lifeExp * pop) %>% 
  group_by(continent, year) %>% 
  summarise(wsum = sum(lifeExpXpop), popSum = sum(pop)) %>% 
  mutate(lifeExp = wsum / popSum) %>% 
  select(-wsum, -popSum)

gapminder_continent %>% 
  ggplot(aes(year, lifeExp, colour = continent)) +
    geom_line() +
    theme_classic()

gapminder_earth = 
  gapminder %>% 
  mutate(lifeExpXpop = lifeExp * pop) %>% 
  group_by(year) %>% 
  summarise(wsum = sum(lifeExpXpop), popSum = sum(pop)) %>% 
  mutate(lifeExp = wsum / popSum) %>% 
  select(-wsum, -popSum)

gapminder_earth %>% 
  ggplot(aes(year, lifeExp)) +
    geom_line() +
    theme_classic()