# Session 1: Getting started with R and RStudio
# Source: https://pierrebeaucoral.github.io/r-for-beginners/
# Open your r-course project in RStudio, then run this file line by line.

library(tidyverse)
library(here)
library(scales)
source(here("R", "theme_cours.R"))
Sys.setenv(LANGUAGE = "en")  # error messages in English

# # Builds "<project root>/data/wdi_panel.csv" on any computer
# here::here("data", "wdi_panel.csv")
# 
# # Used inside a reading function (session 2)
# wdi <- read_csv(here::here("data", "wdi_panel.csv"))

# A comment: R ignores this line
2 + 2   # a comment can also follow code

gdp_usa <- 20.9                                  # a number: US GDP, US$ trillions, 2020
three_countries <- c("USA", "China", "India")    # a vector of texts (see Vectors)
gdp_table <- tibble(country = three_countries,
                    gdp_bn  = c(20894, 14688, 2671))  # a whole table (see Data frames)
gdp_sum <- sum(gdp_table$gdp_bn)                 # the result of a calculation
my_mean <- mean                                  # even a function

gdp_usa            # typing the name recalls the value
gdp_table
my_mean(gdp_table$gdp_bn)   # my_mean now works exactly like mean

ls()

gdp_india <- 2671
gdp_three <- c(20894, 14688, 2671)
gdp_total <- sum(gdp_three)

gdp_total            # (b) recall by name

largest <- max       # (c) a function stored under a new name
largest(gdp_three)

gdp_usa <- 20.9          # numeric
country <- "United States"  # character (text, always in quotes)
is_rich <- TRUE          # logical (TRUE or FALSE, no quotes)

gdp_usa
country
is_rich

class(gdp_usa)
class(country)
class(is_rich)

3 + 5      # addition
10 - 4     # subtraction
6 * 7      # multiplication
20 / 4     # division
2^3        # power
17 %/% 5   # integer division
17 %% 5    # remainder

3 == 3     # equal (two equal signs!)
5 != 4     # different
7 > 5
2 < 6
4 >= 4

TRUE & FALSE
TRUE | FALSE
!TRUE

sqrt(16)
round(3.14159, digits = 2)
round(3.14159, 2)      # same, by position
mean(c(4, 8, 15, 16, 23, 42))

total_gdp <- sum(20.9, 14.7, 2.7)
total_gdp

pop_india <- 1380                     # millions, rounded 2020
pop_three <- 331 + 1411 + pop_india   # computed once, from the value 1380
pop_india <- 1400                     # we change pop_india...
pop_three                             # ...pop_three still holds the old total

# gdp_bn <- c(20894, 14688, 2671)          # GDP, US$ billions, 2020
# gdp_pc <- gdp_bn * 1000 / pop_mn         # GDP per capita, US$
# gdp_pc

try({
# gdp_bn <- c(20894, 14688, 2671)          # GDP, US$ billions, 2020
# gdp_pc <- gdp_bn * 1000 / pop_mn         # GDP per capita, US$
})

gdp_bn <- c(20894, 14688, 2671)          # GDP, US$ billions, 2020
pop_mn <- c(331, 1411, 1380)             # population, millions, 2020
gdp_pc <- gdp_bn * 1000 / pop_mn         # GDP per capita, US$
gdp_pc

# ?mean
# help("round")

# # Step 1, once, in the console: every package used in this course
# install.packages(c(
#   "tidyverse", "here", "janitor", "readxl", "writexl", "lubridate", "scales",
#   "WDI", "gt", "fixest", "modelsummary", "ggrepel", "sf", "rnaturalearth",
#   "rnaturalearthdata", "patchwork", "plotly", "crosstalk", "shiny"
# ))
# 
# # Step 2, at the top of every script
# library(tidyverse)

try({
# gdp_china <- 14.7
# gdp_chinaa + 1      # typo in the name
})

try({
# c(1 2 3)            # missing commas
})

try({
# feols(gdp ~ year, data = tibble(gdp = 1:3, year = 1:3))
})

pop_text <- c("331", "1,411", "1380")   # numbers stored as text
as.numeric(pop_text)

gdp_3 <- read_csv(here("data", "wdi_3countries.csv"))

population <- c(331, 1411, 1380)             # numeric
countries  <- c("USA", "China", "India")     # character
high_income <- c(TRUE, FALSE, FALSE)         # logical

1:10                      # integers from 1 to 10
seq(1, 10, by = 2)        # step of 2
seq(0, 1, length.out = 5) # 5 equally spaced values
rep(5, times = 3)
rep(c("a", "b"), each = 2)

population[2]                # second element
population[c(1, 3)]          # first and third
population[-1]               # all except the first
population[population > 1000]  # elements satisfying a condition
countries[population > 1000]   # use one vector to filter another

population + 2
population * 1000000         # millions to persons
population / sum(population) # share of the total

tibble(country = countries, population = population,
       share = 100 * population / sum(population)) |>
  mutate(country = fct_reorder(country, share)) |>
  ggplot(aes(x = share, y = country)) +
  geom_col(fill = pal_cours[["principal"]]) +
  geom_text(aes(label = paste0(round(share), "%")), hjust = -0.2) +
  scale_x_continuous(limits = c(0, 55)) +
  labs(
    title = "China and India hold 89% of the three countries' population",
    x = "Share of the total population of the three countries (%)",
    y = NULL,
    caption = "Source: rounded 2020 values from an earlier WDI release (World Bank), for teaching."
  )

gini <- c(41.5, 38.2, NA, 35.7)
mean(gini)
mean(gini, na.rm = TRUE)   # na.rm = TRUE: drop NAs before computing
is.na(gini)
sum(is.na(gini))           # how many missing values

read_csv(here("data", "wdi_panel.csv"), show_col_types = FALSE) |>
  filter(year == 2019, !is.na(income)) |>
  summarise(share_na = 100 * mean(is.na(gini)), .by = income) |>
  mutate(income = factor(income, levels = c("Low income", "Lower middle income",
                                            "Upper middle income", "High income"))) |>
  ggplot(aes(x = income, y = share_na)) +
  geom_col(fill = pal_cours[["accent"]]) +
  geom_text(aes(label = paste0(round(share_na), "%")), vjust = -0.4) +
  scale_y_continuous(limits = c(0, 100)) +
  labs(
    title = "Gini is missing for most countries in a single year",
    x = "World Bank income group (current classification)",
    y = "Countries with a missing Gini, 2019 (%)",
    caption = "Source: World Bank, World Development Indicators (WDI), 2019."
  )

countries3 <- tibble(
  country    = c("United States", "China", "India"),
  gdp_bn     = c(20894, 14688, 2671),   # GDP, current US$ billions, rounded 2020
  pop_mn     = c(331, 1411, 1380),      # population, millions, rounded 2020
  high_income = c(TRUE, FALSE, FALSE)
)
countries3

nrow(countries3)     # number of rows
ncol(countries3)     # number of columns
names(countries3)    # column names
str(countries3)      # structure: type of each column
summary(countries3)  # quick statistics per column
head(countries3, 2)  # first 2 rows

countries3$gdp_bn          # one column (a vector) with $
countries3[1, ]            # first row, all columns
countries3[ , "country"]   # all rows, one column
countries3[2, "pop_mn"]    # one cell
countries3[countries3$pop_mn > 1380, ]  # rows satisfying a condition

countries3$gdp_pc <- countries3$gdp_bn * 1000 / countries3$pop_mn
countries3

# Sort by GDP per capita, highest first
countries3[order(countries3$gdp_pc, decreasing = TRUE), ]

# Keep only countries with more than 1,000 million inhabitants
countries3[countries3$pop_mn > 1000, ]

countries3[order(countries3$gdp_pc, decreasing = TRUE), c("country", "gdp_pc")]

countries3 |>
  mutate(country = fct_reorder(country, gdp_pc)) |>
  ggplot(aes(x = gdp_pc, y = country)) +
  geom_col(fill = pal_cours[["principal"]]) +
  geom_text(aes(label = label_dollar()(round(gdp_pc))), hjust = -0.1) +
  scale_x_continuous(limits = c(0, 80000), labels = label_dollar()) +
  labs(
    title = "The US produces six times more per person than China",
    x = "GDP per capita (current US$, 2020)",
    y = NULL,
    caption = "Source: rounded 2020 values from an earlier WDI release (World Bank), for teaching."
  )

sqrt(sum(c(1, 4, 9)))          # nested: read from the inside out

c(1, 4, 9) |> sum() |> sqrt()  # piped: "take c(1, 4, 9), then sum, then sqrt"

c(1, 4, 9)                     # step 1: the data
c(1, 4, 9) |> sum()            # steps 1 and 2
c(1, 4, 9) |> sum() |> sqrt()  # the full chain

my_age <- 25
my_name <- "Pierre"
is_student <- TRUE

my_age
my_name
is_student

class(my_age)
class(my_name)
class(is_student)

x <- 12
y <- 5

x + y
x - y
x * y
x / y

x > y
x %% y == 0   # FALSE: the remainder is 2

# ?round

round(pi, digits = 3)

gdp_growth <- c(2.3, 5.1, NA, 3.8, -0.4)

mean(gdp_growth)                 # NA
mean(gdp_growth, na.rm = TRUE)   # 2.7

# Careful: comparing NA with 2 gives NA, so remove the NA first
gdp_growth[!is.na(gdp_growth) & gdp_growth > 2]

v <- 1:10

v^2
v[v %% 2 == 0]
seq(1, 9, by = 2)

students <- tibble(
  name       = c("Alice", "Bob", "Charlie", "Dalia"),
  age        = c(19, 24, 31, 22),
  is_student = c(TRUE, TRUE, FALSE, TRUE)
)

students$age                       # (a)
students[1, ]                      # (b)
students[students$age > 20, ]      # (c) condition on age only
students[order(students$age), ]    # (d)

countries3$gdp_share <- 100 * countries3$gdp_bn / sum(countries3$gdp_bn)

countries3[order(countries3$gdp_share, decreasing = TRUE),
           c("country", "gdp_share")]
