Data Cleaning

Set up

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   4.0.0     ✔ tibble    3.3.0
✔ lubridate 1.9.4     ✔ tidyr     1.3.1
✔ purrr     1.1.0     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

Load data

# import CO2 Emission and GNI datasets
carbon <- read_csv("data/carbon.csv")
Rows: 26509 Columns: 4
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (2): Entity, Code
dbl (2): Year, emissions_total_per_capita

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
gni <- read_csv("data/gni.csv")
Rows: 4701 Columns: 4
── Column specification ────────────────────────────────────────────────────────
Delimiter: ","
chr (2): Entity, Code
dbl (2): Year, GNI per capita, PPP (constant 2021 international $)

ℹ Use `spec()` to retrieve the full column specification for this data.
ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Data Wrangling

# change data column names
carbon_cleaned <- carbon |> 
    rename("country" = Entity,
         "code" = Code,
         "year" = Year,
         "emissions" = emissions_total_per_capita)

gni_cleaned <- gni |> 
    rename("country" = Entity,
         "code" = Code,
         "year" = Year,
         "gni" = `GNI per capita, PPP (constant 2021 international $)`)
# change data types
carbon_cleaned <- carbon_cleaned |> 
  mutate(year = as.integer(year))
glimpse(carbon_cleaned)
Rows: 26,509
Columns: 4
$ country   <chr> "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", …
$ code      <chr> "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG", "AFG…
$ year      <int> 1949, 1950, 1951, 1952, 1953, 1954, 1955, 1956, 1957, 1958, …
$ emissions <dbl> 0.001992146, 0.010837197, 0.011625335, 0.011467511, 0.013123…
gni_cleaned <- gni_cleaned |> 
  mutate(year = as.integer(year))
glimpse(gni_cleaned)
Rows: 4,701
Columns: 4
$ country <chr> "Afghanistan", "Afghanistan", "Afghanistan", "Afghanistan", "A…
$ code    <chr> "AFG", "AFG", "AFG", "AFG", "ALB", "ALB", "ALB", "ALB", "ALB",…
$ year    <int> 2020, 2021, 2022, 2023, 1995, 1996, 1997, 1998, 1999, 2000, 20…
$ gni     <dbl> 2817.996, 2157.112, 1979.530, 2050.867, 4975.941, 5368.310, 47…

Save the cleaned data

# save two cleaned datasets into RData file
save(carbon_cleaned, file = "data/carbon_cleaned.RData")
save(gni_cleaned, file = "data/gni_cleaned.RData")