What we learned last week:
.csv filesselect() – select variablesfilter() – select observationsmutate() – create new variablesarrange() – order observations%>% – pipingSuppose we want to load the tidyverse and
gapminder packages.
An incorrect approach:
library(tidyverse)
library(gapminder)
Another incorrect approach:
library(pacman)
p_load(tidyverse)
p_load(gapminder)
The correct approach:
library(pacman)
p_load(tidyverse, gapminder)
%>% (Review)Recall that the pipe operator, %>%, passes an object
to a function as an input.
An incorrect approach to applying multiple functions in succession:
df <- select(mtcars, mpg, wt) # select `mpg` and `wt` columns from mtcars
df <- filter(df, mpg >= 20) # select observations with `mpg` > or = 20
df <- arrange(df, mpg) # order observations with respect to `mpg`
Another incorrect approach:
df <- arrange(filter(select(mtcars, mpg, wt), mpg >= 20), mpg)
The correct approach using the pipe operator:
df <- mtcars %>%
select(mpg, wt) %>% # `select()` receives `mtcars`
filter(mpg >= 20) %>% # `filter()` receives `mtcars %>% select()`
arrange(mpg) # `arrange()` receives `mtcars %>% select() %>% filter()`
As econometricians, we sometimes want to aggregate and produce summary statistics about our data.
Recall the gapminder dataset:
head(gapminder)
## # A tibble: 6 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1952 28.8 8425333 779.
## 2 Afghanistan Asia 1957 30.3 9240934 821.
## 3 Afghanistan Asia 1962 32.0 10267083 853.
## 4 Afghanistan Asia 1967 34.0 11537966 836.
## 5 Afghanistan Asia 1972 36.1 13079460 740.
## 6 Afghanistan Asia 1977 38.4 14880372 786.
What is the average/smallest/greatest life expectancy across all countries over the entire sample period?
What is the total GDP of the world in the year 1997?
What is the average/smallest/greatest life expectancy over the entire sample period in each continent?
What is the average/smallest/greatest life expectancy in each year in each continent?
What is the total GDP in each year in each continent?
The above questions can be answered with the aid of the
summarize() and group_by functions, available
through tidyverse.
summarize()The summarize() function takes a dataset as an input,
along with instructions on how to summarize the given data and store the
indicated summary into a new tibble as a variable (or multiple
variables).
Simple example:
gapminder %>%
summarize(avgLifeExp = mean(lifeExp))
## # A tibble: 1 x 1
## avgLifeExp
## <dbl>
## 1 59.5
In the above code chunk, we’ve given summarize() a data
input of gapminder, and then told it to compute the average
of the lifeExp column using mean(), and store
the output into a variable called avgLifeExp.
Now let’s move on to other questions, and combine
summarize() with other familiar functions
(filter(), select(), mutate(),
arrange()).
What was the average life expectancy in 1997?
gapminder %>%
filter(year == 1997) %>%
summarize(avgLifeExp = mean(lifeExp))
## # A tibble: 1 x 1
## avgLifeExp
## <dbl>
## 1 65.0
What was the total GDP of the world in 1997 (in billions of USD)?
gapminder %>%
filter(year == 1997) %>%
mutate(gdp = pop * gdpPercap) %>%
summarize(totGDP = sum(gdp)/(10^9))
## # A tibble: 1 x 1
## totGDP
## <dbl>
## 1 41006.
We can answer both of the above questions inside of a single
summarize() command:
gapminder %>%
filter(year == 1997) %>%
mutate(gdp = pop * gdpPercap) %>%
summarize(avgLifeExp = mean(lifeExp),
totGDP = sum(gdp)/(10^9))
## # A tibble: 1 x 2
## avgLifeExp totGDP
## <dbl> <dbl>
## 1 65.0 41006.
You can use the following functions inside of
summarize():
mean()sum()median()min()max()group_by()The group_by() function allows us to group the
observations in a dataset into different categories.
For example, in the gapminder dataset, we know that each
observation is associated with a specific country, located in a specific
continent, at a specific point in time.
Therefore, we could partition our data by
group_by(country))group_by(continent))group_by(year))group_by(country, year))group_by(continent, year))and produce summary statistics for each partition of the data.
Let’s see group_by() in action by answering some
questions about the gapminder data.
What is the total GDP (in billions of USD) of each continent in the year 1997?
gapminder %>%
filter(year == 1997) %>%
group_by(continent) %>% #
mutate(gdp = pop * gdpPercap) %>%
summarize(avgLifeExp = mean(lifeExp),
totGDP = sum(gdp)/(10^9))
## # A tibble: 5 x 3
## continent avgLifeExp totGDP
## * <fct> <dbl> <dbl>
## 1 Africa 53.6 1561.
## 2 Americas 71.2 14567.
## 3 Asia 68.0 12791.
## 4 Europe 75.5 11508.
## 5 Oceania 78.2 579.
What is the total world GDP (in billions of USD) in each year of the sample?
gapminder %>%
group_by(year) %>%
mutate(gdp = pop * gdpPercap) %>%
summarize(avgLifeExp = mean(lifeExp),
totGDP = sum(gdp)/(10^9))
## # A tibble: 12 x 3
## year avgLifeExp totGDP
## * <int> <dbl> <dbl>
## 1 1952 49.1 7038.
## 2 1957 51.5 8896.
## 3 1962 53.6 11004.
## 4 1967 55.7 14248.
## 5 1972 57.6 18421.
## 6 1977 59.6 22318.
## 7 1982 61.5 25382.
## 8 1987 63.2 30133.
## 9 1992 64.2 34501.
## 10 1997 65.0 41006.
## 11 2002 65.7 47266.
## 12 2007 67.0 58109.
What is the total GDP (in billions of USD) of each continent in each year of the sample?
gapminder %>%
group_by(continent, year) %>% #
mutate(gdp = pop * gdpPercap) %>%
summarize(avgLifeExp = mean(lifeExp),
totGDP = sum(gdp)/(10^9))
## # A tibble: 60 x 4
## # Groups: continent [5]
## continent year avgLifeExp totGDP
## <fct> <int> <dbl> <dbl>
## 1 Africa 1952 39.1 312.
## 2 Africa 1957 41.3 383.
## 3 Africa 1962 43.3 457.
## 4 Africa 1967 45.3 595.
## 5 Africa 1972 47.5 784.
## 6 Africa 1977 49.6 972.
## 7 Africa 1982 51.6 1146.
## 8 Africa 1987 53.3 1254.
## 9 Africa 1992 53.6 1365.
## 10 Africa 1997 53.6 1561.
## # ... with 50 more rows
ggplot2ggplot2 is a package that lives inside
tidyverse (tidyverse is actually a package
that contains a group of packages, each of which contains a group of
functions).
ggplot2 allows us to neatly visualize data!
Many academic researchers and data scientists exclusively use
ggplot2 to make graphs.
Today we will learn the basics of ggplot2 and work
through some examples.
Click here for a wonderful free text on using ggplot.
Suppose I want to focus on gapminder data of the year
1997.
data_97_df <- gapminder %>%
filter(year == 1997)
I suspect that GDP per capita and life expectancy are likely to be positive correlated – in other words, higher life expectancy is likely to be associated with higher GDP per capita, and vice versa.
Let’s test this hypothesis non-rigorously by plotting the data in a scatterplot:
ggplot(data_97_df, aes(x = gdpPercap, y = lifeExp)) + # Contents of the graph
geom_point() # Type of graph
Seems like my hypothesis was correct (for the year 1997, at least).
I know that each data point in the above scatter plot is associated with a country, but which continent is each point associated with?
I would like for my graph to show me the continent associated with each point by assigning a color to each continent, and then coloring its corresponding data points accordingly.
ggplot(data_97_df, aes(x = gdpPercap,
y = lifeExp,
color = continent)) +
geom_point()
Great! But I’m still not quite happy with the above graph.
The points look a little too small.
We can modify the properties of the plot inside of
geom_point.
To change point size, we can simply set size = x, where
x is some numeric value.
ggplot(data_97_df, aes(x = gdpPercap,
y = lifeExp,
color = continent)) +
geom_point(size = 2.5)
Let’s also add a title using ggtitle(), as well as axis
and legend labels using labs().
ggplot(data_97_df, aes(x = gdpPercap/1000,
y = lifeExp,
color = continent)) +
geom_point(size = 2.5) +
ggtitle("Life Expectancy vs. Output") +
labs(x = "GDP per capita (USD, 1000s)",
y = "Life Expectancy (Years)",
color = "Continent")
Lastly, we can manually set the intervals of the x and y axes using
xlim() and ylim(), respectively.
ggplot(data_97_df, aes(x = gdpPercap/1000,
y = lifeExp,
color = continent)) +
geom_point(size = 2.5) +
ggtitle("Life Expectancy vs. Output") +
labs(x = "GDP per capita (USD, 1000s)",
y = "Life Expectancy (Years)",
color = "Continent") +
ylim(0,100) +
xlim(0,50)
Now let’s move on to line plots.
Line plots are often used to visualize the changes in a variable over time.
Suppose I am interested in the average GDP per capita of each
continent for each year in my gapminder sample – I can use
group_by() and summarize() to obtain this type
of aggregated data from the raw country-level data.
continent_allyears_df <- gapminder %>%
group_by(year, continent) %>%
summarize(avgGDPPercap = mean(gdpPercap))
continent_allyears_df
## # A tibble: 60 x 3
## # Groups: year [12]
## year continent avgGDPPercap
## <int> <fct> <dbl>
## 1 1952 Africa 1253.
## 2 1952 Americas 4079.
## 3 1952 Asia 5195.
## 4 1952 Europe 5661.
## 5 1952 Oceania 10298.
## 6 1957 Africa 1385.
## 7 1957 Americas 4616.
## 8 1957 Asia 5788.
## 9 1957 Europe 6963.
## 10 1957 Oceania 11599.
## # ... with 50 more rows
I can now create a line graph of my continent-level data, in which the x-axis represents time and the y-axis represents the average GDP per capita in 1000s of USD.
ggplot(continent_allyears_df,
aes(x = year,
y = avgGDPPercap/1000,
color = continent)) +
geom_line()
We can improve the plot by making the lines thicker and adding title, axis, and legend labels.
ggplot(continent_allyears_df,
aes(x = year,
y = avgGDPPercap/1000,
color = continent)) +
geom_line(size = 1) +
ggtitle("Continent GDP per capita Over Time") +
labs(x = "Year",
y = "Average GDP per capita (USD, 1000s)",
color = "Continent")
The may further improve the plot by getting rid of excess empty intervals on the x-axis.
ggplot(continent_allyears_df,
aes(x = year, y = avgGDPPercap/1000, color = continent)) +
geom_line(size = 1) +
ggtitle("Continent GDP per capita Over Time") +
labs(x = "Year",
y = "Average GDP per capita (USD, 1000s)",
color = "Continent") +
scale_x_continuous(expand = c(0,0))
Sometimes we want to check the distributions of variables within our sample – to do so we may use histograms.
Suppose we’re interested in checking the distribution of life
expectancy in a subsample of gapminder containing
observations from only the years 1957 and 2007.
data_57_97_df <- gapminder %>%
filter(year %in% c(1957,2007))
data_57_97_df
## # A tibble: 284 x 6
## country continent year lifeExp pop gdpPercap
## <fct> <fct> <int> <dbl> <int> <dbl>
## 1 Afghanistan Asia 1957 30.3 9240934 821.
## 2 Afghanistan Asia 2007 43.8 31889923 975.
## 3 Albania Europe 1957 59.3 1476505 1942.
## 4 Albania Europe 2007 76.4 3600523 5937.
## 5 Algeria Africa 1957 45.7 10270856 3014.
## 6 Algeria Africa 2007 72.3 33333216 6223.
## 7 Angola Africa 1957 32.0 4561361 3828.
## 8 Angola Africa 2007 42.7 12420476 4797.
## 9 Argentina Americas 1957 64.4 19610538 6857.
## 10 Argentina Americas 2007 75.3 40301927 12779.
## # ... with 274 more rows
The conditional statement year %in% c(1957,2007) checks
whether for each given observation year equals either 1957
or 2007 – if TRUE, then filter() keeps these
observations.
We may now plot a simple histogram of lifeExp using this
newly-constructed subsample of gapminder.
ggplot(data_57_97_df, aes(lifeExp)) +
geom_histogram()
Add title and axis labels:
ggplot(data_57_97_df, aes(lifeExp)) +
geom_histogram() +
ggtitle("Life Expectancy Frequency Plot") +
labs(x = "Life Expectancy (Years)",
y = "Count")
Intuitively, the distribution of lifeExp in this
subsample is bimodal.
This is because there are two distinct distributions generating two sets of observations in our dataset – life expectancy in 1957 for each country is likely to be much lower than in 1997.
Let’s group the observations in our histogram by year:
ggplot(data_57_97_df, aes(lifeExp, fill = factor(year))) +
geom_histogram() +
ggtitle("Life Expectancy Frequency Plot") +
labs(x = "Life Expectancy (Years)",
y = "Count",
fill = "Year")
Perhaps we would like to make the bins wider:
ggplot(data_57_97_df, aes(lifeExp, fill = factor(year))) +
geom_histogram(binwidth = 5) +
ggtitle("Life Expectancy Frequency Plot") +
labs(x = "Life Expectancy (Years)",
y = "Count",
fill = "Year")
Instead of stacking the two groups of data on top of each other, we might instead like to give each group a separate bar per bin:
ggplot(data_57_97_df, aes(lifeExp, fill = factor(year))) +
geom_histogram( binwidth = 5,
position = "dodge") +
ggtitle("Life Expectancy Frequency Plot") +
labs(x = "Life Expectancy (Years)",
y = "Count",
fill = "Year")