---
title: "Case Study: Income by Religion"
author: "Keith VanderLinden"
date: "Spring, 2022"
output: html_document
---

```{r include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

```{r warning = FALSE, message = FALSE}
library(tidyverse)
```

This document reproduces an analysis of income distributed by religious group made by the [Pew Religious Landscape Study](https://www.pewforum.org/religious-landscape-study/income-distribution/) based on data collected by the Pew Research Center and downloaded on April 14, 2020.

## Loading the Dataset

The dataset is stored as an Excel file.

```{r}
library(readxl)

income_religion <- read_excel("data/income-religion.xlsx")
income_religion
```

## Wrangling &amp; Tidying the Dataset

We now massage the dataset to:
- Rename the columns to make them easier to work with.
- Pivot the percentages into a single column for presentation.
- Factorize the religious tradition name to set its order.
- Add a frequency count

```{r}
income_religion_long <- income_religion %>%
  rename(
    religion = `Religious tradition`,
    n = `Sample Size`
  ) %>%
  pivot_longer(
    cols = -c(religion, n), 
    names_to = "income", 
    values_to = "proportion"
  ) %>%
  mutate(
    religion = fct_rev(religion), 
    income = fct_relevel(income, 
                         "$100,000 or more",
                         "$50,000−$99,999", 
                         "$30,000−$49,999",
                         "Less than $30,000"),
    frequency = round(proportion * n)
  )
income_religion_long
```

## Reproducing the Plot

With the dataset in place, we can now build an approximation of Pew&rsquo;s plot.

```{r}
income_religion_long %>%
  ggplot() +
  aes(x = frequency,
      y = religion, 
      fill = income,
      ) +
  geom_col(
    position = "fill"
  ) +
  scale_fill_viridis_d() +
  theme_minimal() +
  theme(
   legend.position = "bottom",
   legend.key.size = unit(0.2, "cm"),
    ) +
  guides(
    fill = guide_legend(reverse = TRUE)
    ) +
  labs(
    x = "Frequency", y = "",
    title = "Income distribution by religious group",
    subtitle = "% of adults who have a household income of...",
    caption = "Source: Pew Research Center, Religious Landscape Study",
    fill = NULL,
    )
```
