---
title: "Exploring Descriptive Statistics and Aggregation with R"
subtitle: "Using the Gapminder Dataset"
author: "Your Name Here"
date: "`r Sys.Date()`"
output:
  word_document: default
  pdf_document: default
  html_document: default
---

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

# Activity 1: Reading Data into R

## Task 2: Load the Gapminder Dataset

### Option 1: From R Package (Recommended)

```{r load-package}
# Install the gapminder package if not already installed
if (!require(gapminder)) {
  install.packages("gapminder")
}

# Load required libraries
library(gapminder)
library(dplyr)

# Load the dataset
data(gapminder)
```

### Option 2: From CSV (Alternative)

```{r load-csv, eval=FALSE}
# If using a CSV file instead:
# gapminder <- read.csv("path/to/gapminder.csv")
```

## Task 3: Basic Exploration

```{r explore-data}
# View first 6 rows
head(gapminder)

# View last 6 rows
tail(gapminder)

# Structure of the dataset
str(gapminder)

# Summary statistics for all variables
summary(gapminder)

# Detailed glimpse of the data (from dplyr)
glimpse(gapminder)

# Dimensions of the dataset
dim(gapminder)
```

## Task 4: Brief Summary of the Dataset

**About the Dataset:**
The Gapminder dataset contains information about `r nrow(gapminder)` observations across `r ncol(gapminder)` variables. It tracks development indicators for `r length(unique(gapminder$country))` countries across `r length(unique(gapminder$continent))` continents from `r min(gapminder$year)` to `r max(gapminder$year)`.

**Variables and Data Types:**

- **country** (Factor): Name of the country
- **continent** (Factor): Continent the country belongs to (Africa, Americas, Asia, Europe, Oceania)
- **year** (Integer): Year of observation
- **lifeExp** (Numeric): Life expectancy at birth (in years)
- **pop** (Integer): Total population
- **gdpPercap** (Numeric): GDP per capita (US$, inflation-adjusted)

---

# Activity 2: Central Tendency

## Mean

The mean (average) of life expectancy across all observations:

```{r mean}
mean(gapminder$lifeExp)
```

**Interpretation:** The average life expectancy across all countries and years in the dataset is approximately `r round(mean(gapminder$lifeExp), 2)` years.

## Median

The median of life expectancy:

```{r median}
median(gapminder$lifeExp)
```

**Interpretation:** The median life expectancy is `r round(median(gapminder$lifeExp), 2)` years. Since the median is less than the mean, this suggests the distribution is slightly right-skewed (some countries have notably higher life expectancy).

## Mode

The mode is the most frequently occurring value. R doesn't have a built-in mode function, so we create one:

```{r mode}
# Custom function to calculate mode
getmode <- function(v) {
  uniqv <- unique(v)
  uniqv[which.max(tabulate(match(v, uniqv)))]
}

# Mode of continent (most common continent in dataset)
getmode(gapminder$continent)

# Count observations per continent
table(gapminder$continent)
```

**Interpretation:** The most frequently occurring continent in the dataset is `r getmode(gapminder$continent)`, which appears `r max(table(gapminder$continent))` times.

---

# Activity 3: Measures of Variability

## Variance

```{r variance}
var(gapminder$lifeExp)
```

**Interpretation:** The variance of life expectancy is `r round(var(gapminder$lifeExp), 2)`. This represents the average of squared deviations from the mean.

## Standard Deviation

```{r sd}
sd(gapminder$lifeExp)
```

**Interpretation:** The standard deviation is `r round(sd(gapminder$lifeExp), 2)` years. This means that life expectancy values typically deviate from the mean by about `r round(sd(gapminder$lifeExp), 2)` years.

## Range

```{r range}
range(gapminder$lifeExp)

# Calculate the spread
diff(range(gapminder$lifeExp))
```

**Interpretation:** Life expectancy ranges from `r min(gapminder$lifeExp)` years to `r max(gapminder$lifeExp)` years, giving a total range of `r round(diff(range(gapminder$lifeExp)), 2)` years.

## Summary Statistics (including Quartiles)

```{r summary}
summary(gapminder$lifeExp)
```

**Interpretation:**

- **Q1 (25th percentile):** 25% of observations have life expectancy below `r quantile(gapminder$lifeExp, 0.25)` years
- **Q2 (Median):** 50% of observations are below `r median(gapminder$lifeExp)` years
- **Q3 (75th percentile):** 75% of observations have life expectancy below `r quantile(gapminder$lifeExp, 0.75)` years

## Interquartile Range (IQR)

```{r iqr}
IQR(gapminder$lifeExp)
```

**Interpretation:** The IQR is `r round(IQR(gapminder$lifeExp), 2)` years. This represents the spread of the middle 50% of the data, which is less sensitive to outliers than the full range.

---

# Activity 4: Data Aggregation with dplyr

## Aggregation by Continent

```{r aggregation}
library(dplyr)

# Calculate mean and standard deviation of life expectancy by continent
gapminder %>%
  group_by(continent) %>%
  summarise(
    mean_lifeExp = mean(lifeExp),
    sd_lifeExp = sd(lifeExp)
  )
```

## Additional Aggregation Examples

### Summary statistics by continent (expanded)

```{r aggregation-expanded}
gapminder %>%
  group_by(continent) %>%
  summarise(
    count = n(),
    mean_lifeExp = mean(lifeExp),
    median_lifeExp = median(lifeExp),
    sd_lifeExp = sd(lifeExp),
    min_lifeExp = min(lifeExp),
    max_lifeExp = max(lifeExp),
    IQR_lifeExp = IQR(lifeExp)
  )
```

### Summary statistics by year

```{r aggregation-year}
gapminder %>%
  group_by(year) %>%
  summarise(
    mean_lifeExp = mean(lifeExp),
    mean_gdpPercap = mean(gdpPercap),
    total_pop = sum(as.numeric(pop))
  )
```

### Summary statistics by continent AND year

```{r aggregation-both}
gapminder %>%
  group_by(continent, year) %>%
  summarise(
    mean_lifeExp = mean(lifeExp),
    .groups = "drop"
  ) %>%
  head(15)  # Show first 15 rows
```

---

# Summary & Reflection

In this session, we:

1. **Loaded and explored** the Gapminder dataset using `head()`, `summary()`, `str()`, and `glimpse()`
2. **Calculated measures of central tendency:** mean (`r round(mean(gapminder$lifeExp), 2)`), median (`r round(median(gapminder$lifeExp), 2)`), and mode
3. **Calculated measures of variability:** variance, standard deviation (`r round(sd(gapminder$lifeExp), 2)`), range, and IQR (`r round(IQR(gapminder$lifeExp), 2)`)
4. **Aggregated data** using `group_by()` and `summarise()` from dplyr

**Key Insights:**

- Global average life expectancy in the dataset is approximately 59 years
- There is substantial variation in life expectancy (SD ≈ 13 years)
- Oceania has the highest average life expectancy, while Africa has the lowest
- Life expectancy has generally increased over time across all continents

---

*Document created for Session 3 submission*
