1. Objectives

2. Data Import and Cleaning

Import the datasets directly into R using read.csv(), clean the Spanish number formatting (% symbols, thousands separators, and decimal commas), convert the variables to numeric format, and reorder the rows chronologically from oldest (2015T1) to most recent (2024T4).

# 1. DATA CLEANING

# CLEANING FOR PROJECT DATA

# 1. Load the original dataset as character strings to prevent formatting issues
project_data <- read.csv("project_data.csv", sep = ";", dec = ",", colClasses = "character", fileEncoding = "Latin1")

# 2. Standardize column names (remove accents)
names(project_data)[names(project_data) == "IPC_Variación"] <- "IPC_Variacion"

# 3. Extract numeric year and quarter (removing the 'T')
project_data$Year <- as.numeric(substr(project_data$Periodo, 1, 4))
project_data$Quarter <- as.numeric(substr(project_data$Periodo, 6, 6))

# 4. Sort chronologically (from 2015T1 to 2024T4)
project_data <- project_data[order(project_data$Year, project_data$Quarter), ]

# 5. Clean and convert columns with decimal commas to numeric
project_data$PIB_Indice <- as.numeric(gsub(",", ".", project_data$PIB_Indice))
project_data$IPI_Desestacionalizado_Medio <- as.numeric(gsub(",", ".", project_data$IPI_Desestacionalizado_Medio))

# 6. Remove '%' sign, replace decimal comma with dot, and convert to numeric
project_data$IPC_Variacion <- as.numeric(gsub(",", ".", gsub("%", "", project_data$IPC_Variacion)))
project_data$Tasa_Desempleo <- as.numeric(gsub(",", ".", gsub("%", "", project_data$Tasa_Desempleo)))

# 7. Remove thousand-separator dots and convert to numeric
project_data$Exportacion_Millones <- as.numeric(gsub("\\.", "", project_data$Exportacion_Millones))
project_data$Importacion_Millones <- as.numeric(gsub("\\.", "", project_data$Importacion_Millones))
project_data$Visitantes_Totales <- as.numeric(gsub("\\.", "", project_data$Visitantes_Totales))

# CLEANING FOR TEST DATA

test_data <- read.csv("test_data (1).csv", sep = ";", dec = ",")

names(test_data)[names(test_data) == "IPC_Variación"] <- "IPC_Variacion"

test_data$Year <- as.numeric(substr(test_data$Periodo, 1, 4))
test_data$Quarter <- as.numeric(substr(test_data$Periodo, 6, 6))

# 4. Sort chronologically (from 2015T1 to 2024T4)
test_data <- test_data[order(test_data$Year, test_data$Quarter), ]

test_data$IPI_Desestacionalizado_Medio <- as.numeric(gsub(",", ".", test_data$IPI_Desestacionalizado_Medio))

# 6. Remove '%' sign, replace decimal comma with dot, and convert to numeric
test_data$IPC_Variacion <- as.numeric(gsub(",", ".", gsub("%", "", test_data$IPC_Variacion)))
test_data$Tasa_Desempleo <- as.numeric(gsub(",", ".", gsub("%", "", test_data$Tasa_Desempleo)))

# 7. Remove thousand-separator dots and convert to numeric

test_data$Exportacion_Millones <- as.numeric(gsub("\\.", "", test_data$Exportacion_Millones))
test_data$Importacion_Millones <- as.numeric(gsub("\\.", "", test_data$Importacion_Millones))
test_data$Visitantes_Totales <- as.numeric(gsub("\\.", "", test_data$Visitantes_Totales))

print(test_data)
  Periodo IPC_Variacion Tasa_Desempleo Exportacion_Millones
5  2025T1         0.623          11.36               141295
4  2025T2         1.370          10.29               146882
3  2025T3        -0.850          10.15               143158
2  2025T4         1.150           9.85               154583
1  2026T1         0.950          10.65               148619
  Importacion_Millones Visitantes_Totales IPI_Desestacionalizado_Medio Year
5               131785           27440002                     101.4637 2025
4               134710           17055977                     102.2830 2025
3               136902           32541200                     100.8541 2025
2               141271           21105430                     102.1542 2025
1               135545           18240500                     101.8945 2026
  Quarter
5       1
4       2
3       3
2       4
1       1
# CLEANING FOR TRAIN DATA

train_data <- read.csv("train_data (1).csv", sep = ";", dec = ",", colClasses = "character", fileEncoding = "Latin1")

names(train_data)[names(train_data) == "IPC_Variación"] <- "IPC_Variacion"

train_data$Year <- as.numeric(substr(train_data$Periodo, 1, 4))
train_data$Quarter <- as.numeric(substr(train_data$Periodo, 6, 6))

train_data$IPI_Desestacionalizado_Medio <- as.numeric(gsub(",", ".", train_data$IPI_Desestacionalizado_Medio))

# 6. Remove '%' sign, replace decimal comma with dot, and convert to numeric
train_data$PIB_Indice <- as.numeric(gsub(",", ".", train_data$PIB_Indice))
train_data$IPC_Variacion <- as.numeric(gsub(",", ".", gsub("%", "", train_data$IPC_Variacion)))
train_data$Tasa_Desempleo <- as.numeric(gsub(",", ".", gsub("%", "", train_data$Tasa_Desempleo)))

# 7. Remove thousand-separator dots and convert to numeric

train_data$Exportacion_Millones <- as.numeric(gsub("\\.", "", train_data$Exportacion_Millones))
train_data$Importacion_Millones <- as.numeric(gsub("\\.", "", train_data$Importacion_Millones))
train_data$Visitantes_Totales <- as.numeric(gsub("\\.", "", train_data$Visitantes_Totales))

3. Reorder chronologically from oldest (2015T1) to most recent (2024T4) project_data <- project_data[order(project_data$Periodo), ]

project_data <- project_data[order(project_data$Year, project_data$Quarter), ]

train_data <- train_data[order(train_data$Year, train_data$Quarter), ]
print(train_data)
   Periodo PIB_Indice IPC_Variacion Tasa_Desempleo Exportacion_Millones
80  2005T1    98.0000         3.400          10.19                66400
79  2005T2    98.9000         3.100           9.33                70500
78  2005T3    99.8000         3.700           8.42                67100
77  2005T4   100.7000         3.700           8.70                68200
76  2006T1   101.8000         3.900           9.07                69800
75  2006T2   102.9000         3.900           8.53                73400
74  2006T3   103.8000         2.900           8.15                70100
73  2006T4   104.9000         2.700           8.30                71500
72  2007T1   106.0000         2.500           8.47                72800
71  2007T2   107.1000         2.400           7.95                76200
70  2007T3   107.9000         2.700           8.03                73500
69  2007T4   108.8000         4.200           8.60                75100
68  2008T1   109.1000         4.500           9.60                74200
67  2008T2   109.2000         5.000          10.44                76800
66  2008T3   108.8000         4.500          11.33                73100
65  2008T4   107.5000         1.400          13.91                74500
64  2009T1   104.1000        -0.100          17.36                67800
63  2009T2   102.4000        -1.400          17.92                71200
62  2009T3   102.1000        -1.000          17.92                68500
61  2009T4   102.2000         0.800          18.83                70100
60  2010T1   102.4000         1.400          20.05                69500
59  2010T2   102.6000         1.500          20.09                72800
58  2010T3   102.6000         2.100          19.79                71100
57  2010T4   102.8000         3.000          20.33                73400
56  2011T1   103.1000         3.300          21.29                72500
55  2011T2   103.3000         3.200          20.89                76100
54  2011T3   103.1000         3.100          21.52                73200
53  2011T4   102.5000         2.400          22.85                75800
52  2012T1   101.2000         1.900          24.44                74100
51  2012T2   100.1000         1.900          24.63                77500
50  2012T3    99.2000         3.400          25.02                75100
49  2012T4    98.1500         2.900          26.02                76900
48  2013T1    97.3500         2.400          26.94                75200
47  2013T2    97.1000         1.500          26.26                79800
46  2013T3    96.9500         0.320          25.98                76500
45  2013T4    97.1200         0.250          25.73                78100
44  2014T1    97.5020        -0.150          25.93                77400
43  2014T2    97.9100         0.150          24.47                81200
42  2014T3    98.4210        -0.210          23.67                79540
41  2014T4    99.3152        -1.040          23.70                80120
40  2015T1   100.0285        -0.775          23.78                83560
39  2015T2   101.1486         1.672          22.37                92115
38  2015T3   102.0763        -1.561          21.18                90655
37  2015T4   102.9879         0.714          20.90                91442
36  2016T1   103.7035        -1.627          21.00                87650
35  2016T2   104.0465         1.719          20.00                96112
34  2016T3   104.8690        -0.595          18.91                95655
33  2016T4   105.4650         2.111          18.63                95091
32  2017T1   106.2117        -0.928          18.75                94939
31  2017T2   107.3223         0.943          17.22               102183
30  2017T3   108.0003        -0.318          16.38               101876
29  2017T4   108.6577         1.429          16.55               101218
28  2018T1   109.1224        -0.829          16.74                97654
27  2018T2   109.8339         2.001          15.28               107187
26  2018T3   110.4471        -0.333          14.55               105082
25  2018T4   111.0935         0.362          14.45               104239
24  2019T1   111.7746        -0.678          14.70                98345
23  2019T2   112.0969         1.086          14.02               109251
22  2019T3   112.3117        -0.675          13.92               105082
21  2019T4   112.9526         1.068          13.78               104239
20  2020T1   107.1046        -1.472          14.41                84110
19  2020T2    88.0503         0.758          15.33                58420
18  2020T3   102.0523        -0.703          16.26                78115
17  2020T4   102.7928         0.904          16.13                87940
16  2021T1   104.0281         0.384          15.98                85340
15  2021T2   105.4542         2.141          15.26                96115
14  2021T3   107.5329         0.529          14.57                94210
13  2021T4   109.7174         3.371          13.33               108971
12  2022T1   111.1911         3.464          13.65               114731
11  2022T2   113.1088         2.511          12.48               131844
10  2022T3   114.0752        -0.697          12.67               126790
9   2022T4   114.7266         0.366          12.87               141488
8   2023T1   115.4976         1.103          13.38               142548
7   2023T2   115.7820         1.119          11.67               142791
6   2023T3   116.5446         0.885          11.89               134156
5   2023T4   117.4009        -0.035          11.80               138021
4   2024T1   118.6446         1.206          12.29               138021
3   2024T2   119.5593         1.341          11.27               138584
2   2024T3   120.4020        -1.035          11.21               138584
1   2024T4   121.2745         1.326          10.61               150311
   Importacion_Millones Visitantes_Totales IPI_Desestacionalizado_Medio Year
80                80200            8100500                     114.5000 2005
79                85400           13800100                     115.8000 2005
78                81100           18900200                     116.2000 2005
77                82500           10100300                     117.5000 2005
76                83100            8400100                     118.1000 2006
75                88200           14200500                     119.5000 2006
74                84500           19500400                     120.2000 2006
73                86100           10400200                     121.0000 2006
72                87400            8700100                     123.5000 2007
71                91500           14800300                     124.1000 2007
70                88100           20100200                     122.8000 2007
69                90200           10800500                     121.5000 2007
68                87500            8900200                     120.1000 2008
67                89100           15100400                     118.4000 2008
66                83500           20400300                     115.2000 2008
65                85200           10600100                     110.5000 2008
64                70500            8100500                     102.1000 2009
63                74100           14400200                     100.5000 2009
62                71200           19800500                      98.4000 2009
61                73500           10200300                      97.8000 2009
60                72800            8500100                      98.5000 2010
59                75100           14900200                      99.0000 2010
58                71500           20500400                      98.1000 2010
57                74200           10500100                      97.5000 2010
56                73100            8800300                      96.1000 2011
55                75900           15400200                      95.2000 2011
54                71800           21100500                      93.8000 2011
53                74500           10900400                      92.3000 2011
52                72100            9100100                      91.5000 2012
51                75200           15900200                      90.1000 2012
50                71900           21800300                      89.4000 2012
49                73400           11200500                      88.7000 2012
48                70800            9500400                      89.1000 2013
47                74200           16500100                      90.5000 2013
46                70100           22900400                      89.9000 2013
45                72500           11800200                      90.2000 2013
44                71200           10100300                      91.5000 2014
43                76500           17100200                      93.1000 2014
42                73110           23800500                      92.8000 2014
41                75430           12450100                      93.4500 2014
40                79112           10680250                      94.9160 2015
39                82410           18650400                      96.9193 2015
38                80992           25340120                      98.3717 2015
37                83110           13700057                      97.4320 2015
36                81335           11832469                      98.9130 2016
35                85140           20750239                      98.4593 2016
34                84112           27505870                      98.3200 2016
33                85990           15226431                      98.9943 2016
32                87650           12938816                     100.4540 2017
31                93110           23516217                     100.7140 2017
30                91545           29768453                     100.9943 2017
29                92115           15645036                     103.8560 2017
28                92410           13717834                     102.9777 2018
27                98665           23420732                     101.9590 2018
26                97450           29128315                     101.6943 2018
25                99112           16541531                     101.5990 2018
24                96115           14225722                     102.9960 2019
23               101440           23899130                     102.9740 2019
22                97550           28836788                     102.0917 2019
21                99410           16547511                     102.6397 2019
20                83990           10557630                      97.5860 2020
19                60115             204272                      77.9677 2020
18                73190            6044625                      97.2433 2020
17                81332            2126576                     100.1343 2020
16                80320            1214374                     100.1867 2021
15                87892            4208726                      98.6823 2021
14                89155           14299445                      99.3187 2021
13               101442           11458258                     101.8120 2021
12               112981            9720263                     101.1687 2022
11               124960           20592825                     103.7820 2022
10               127345           25707266                     103.1517 2022
9                134020           15638928                     101.5650 2022
8                130252           13703001                     101.5227 2023
7                126877           23835938                     100.7823 2023
6                120015           29098504                     100.2853 2023
5                131810           18531605                     100.3933 2023
4                126312           16139517                     102.2063 2024
3                131066           26339309                     100.7180 2024
2                128178           31383946                     100.0320 2024
1                137994           19896526                     101.6730 2024
   Quarter
80       1
79       2
78       3
77       4
76       1
75       2
74       3
73       4
72       1
71       2
70       3
69       4
68       1
67       2
66       3
65       4
64       1
63       2
62       3
61       4
60       1
59       2
58       3
57       4
56       1
55       2
54       3
53       4
52       1
51       2
50       3
49       4
48       1
47       2
46       3
45       4
44       1
43       2
42       3
41       4
40       1
39       2
38       3
37       4
36       1
35       2
34       3
33       4
32       1
31       2
30       3
29       4
28       1
27       2
26       3
25       4
24       1
23       2
22       3
21       4
20       1
19       2
18       3
17       4
16       1
15       2
14       3
13       4
12       1
11       2
10       3
9        4
8        1
7        2
6        3
5        4
4        1
3        2
2        3
1        4
test_data <- test_data[order(test_data$Year, test_data$Quarter), ]

# Check if the data is in order

4. Test the function on pib_yoy and add the new column to project_data.

The first 4 quarters are set to NA because there is no data for the prior year

# The first 4 quarters are set to NA because there is no data for the prior year

yoy_variation <- function(values) {
  n <- length(values)
  result <- rep(NA, n)
  
  for (t in 5:n) {
    result[t] <- ((values[t] - values[t - 4]) / values[t - 4]) * 100
  }
  
  return(result)
}

project_data$pib_yoy <- yoy_variation(project_data$PIB_Indice)

train_data$pib_yoy <- yoy_variation(train_data$PIB_Indice)

5. Exploratory Analysis

5.1 Descriptive Statistics Table

Generate a single summary table containing the mean, median, standard deviation, minimum, and maximum of all macroeconomic indicators.

indicator_cols <- c(
  "PIB_Indice", "IPC_Variacion", "Tasa_Desempleo",
  "Exportacion_Millones", "Importacion_Millones", "Visitantes_Totales",
  "IPI_Desestacionalizado_Medio", "pib_yoy")

desc_table <- data.frame()

for (col in indicator_cols) {
  row_stats <- data.frame(
    Mean      = mean(project_data[[col]], na.rm = TRUE),
    Median    = median(project_data[[col]], na.rm = TRUE),
    SD        = sd(project_data[[col]], na.rm = TRUE),
    Min       = min(project_data[[col]], na.rm = TRUE),
    Max       = max(project_data[[col]], na.rm = TRUE)
  )
  desc_table <- rbind(desc_table, row_stats)
}

rownames(desc_table) <- indicator_cols
print(desc_table)
                                     Mean       Median           SD
PIB_Indice                   1.092272e+02 1.094199e+02 6.639908e+00
IPC_Variacion                5.563000e-01 7.360000e-01 1.292242e+00
Tasa_Desempleo               1.550425e+01 1.463500e+01 3.313905e+00
Exportacion_Millones         1.073666e+05 1.020295e+05 2.185563e+04
Importacion_Millones         9.995048e+04 9.461250e+04 2.028235e+04
Visitantes_Totales           1.731434e+07 1.634052e+07 8.260146e+06
IPI_Desestacionalizado_Medio 9.993716e+01 1.007160e+02 4.112119e+00
pib_yoy                      2.057345e+00 2.730313e+00 6.092392e+00
                                      Min          Max
PIB_Indice                       88.05030 1.212745e+02
IPC_Variacion                    -1.62700 3.464000e+00
Tasa_Desempleo                   10.61000 2.378000e+01
Exportacion_Millones          58420.00000 1.503110e+05
Importacion_Millones          60115.00000 1.379940e+05
Visitantes_Totales           204272.00000 3.138395e+07
IPI_Desestacionalizado_Medio     77.96770 1.038560e+02
pib_yoy                         -21.45162 1.976586e+01

The summary statistics highlight two distinct economic dynamics across the dataset. For domestic activity (PIB_Indice, IPI_Desestacionalizado_Medio, and pib_yoy), the median exceeds the mean, meaning normal quarters grew steadily while rare downturns pulled the average down. Meanwhile, unemployment (Tasa_Desempleo) and external-sector indicators (Exportacion_Millones, Importacion_Millones, and Visitantes_Totales) show wider spread and right-skewness from structural shifts and seasonality, while inflation (IPC_Variacion) stays anchored.

5.2 Vector indicating units of each indicator, time evolution line chart

units <- c(
  PIB_Indice                   = "Index (Base 2015 = 100)",
  IPC_Variacion                = "YoY Percentage Change (%)",
  Tasa_Desempleo               = "Percentage of Active Population (%)",
  Exportacion_Millones         = "Million Euros (€)",
  Importacion_Millones         = "Million Euros (€)",
  Visitantes_Totales           = "Number of Tourists",
  IPI_Desestacionalizado_Medio = "Index (Base 2015 = 100)",
  pib_yoy                      = "YoY Percentage Growth (%)"
)


#error in R suggested using .data[[variable]] in order to get the information in the dataframe. 
# Since 'period' is a text variable (discrete), group = 1 tells ggplot that all points belong to a single series so geom_line() connects them

for (variable in indicator_cols) {
  chart <- ggplot(project_data, aes(x = Periodo, y = .data[[variable]], group = 1)) +
    geom_line(size = 0.5, alpha = 1) +
    geom_point(size = 1, alpha = 1, color = "navyblue") +
    labs(
      title   = paste("Evolution of", variable, "(2015T1 - 2024T4)"),
      x       = "Quarter",
      y       = units[variable],
      caption = "Project Data"
    ) +
    theme_minimal() +
    theme(axis.text.x = element_text(angle = 45, hjust = 1, size = 8))
  
  print(chart)
}
Warning: Using `size` aesthetic for lines was deprecated in ggplot2 3.4.0.
ℹ Please use `linewidth` instead.
This warning is displayed once per session.
Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
generated.

Warning: Removed 4 rows containing missing values or values outside the scale range
(`geom_line()`).
Warning: Removed 4 rows containing missing values or values outside the scale range
(`geom_point()`).

5.3 Histograms

Create one histogram per indicator to inspect how its values are distributed.

# HISTOGRAMS 

for (n in indicator_cols) {
  df_hist <- data.frame(
    time  = 1:nrow(project_data),
    value = project_data[[n]]
  )
  
 p <- ggplot(df_hist, aes(x = value)) +
    geom_histogram(bins = 20, fill = "navyblue", color = "white") +
    labs(
      title = paste("Value Distribution:", n),
      x     = n,
      y     = "Frequency (Quarters)"
    ) +
    theme_bw()
  
  print(p)
}

Warning: Removed 4 rows containing non-finite outside the scale range
(`stat_bin()`).

The histograms demonstrate the frequency distribution of each variable across quarters: PIB_Indice, IPI_Desestacionalizado_Medio and pib_yoy concentrate around normal growth levels with isolated tail bars reflecting the 2020 COVID-19 shock and subsequent rebound. Meanwhile, trade (Exportacion_Millones and Importacion_Millones) displays a clear pattern separating pre and post-pandemic price/volume regimes, while Tasa_Desempleo, Visitantes_Totales, and IPC_Variacion spread across multiple peaks due to seasonality and structural shifts.

5.4 Boxplots

Create one boxplot per indicator (or several grouped in the same figure if their units allow it) to visualise dispersion and possible outliers.

for (datos in indicator_cols) {
  boxplot <- ggplot(project_data, aes(x = "", y = .data[[datos]])) +
    geom_boxplot(fill = "lightblue", color = "black") +
    labs(
      title   = paste("Distribution of", datos),
      x       = NULL,
      y       = units[datos],
      caption = "Source:Project Data"
    ) +
    theme_minimal()
  
  print(boxplot)
}

Warning: Removed 4 rows containing non-finite outside the scale range
(`stat_boxplot()`).

Complementing the histograms above, the boxplots point each variable’s exact median, interquartile spread and outliers.

5.5 Correlation Heatmap

Create a heatmap between all numerical indicators (including pib_yoy).

cor_table <- cor(project_data[, indicator_cols], use = "complete.obs")
long_data <- melt(cor_table)

for(n in 1:length(indicator_cols)) {
  df_heatmap <- data.frame(
    time  = 1:nrow(project_data),
    value = project_data[[n]]
  )
 op <- ggplot(long_data, aes(Var1, Var2, fill = value)) +
  geom_tile(color = "white") +
  geom_text(aes(label = round(value, 2)), size = 4) +
  scale_fill_gradient2(low = "lightblue", high = "lightgreen", mid = "white", 
                       midpoint = 0, limit = c(-1,1)) +
  theme_bw() + theme(axis.text.x = element_text(angle = 45, hjust = 1))
}

  print(op)

Strong correlations appear between GDP growth (pib_yoy), industrial production (ipi_yoy), and unemployment (Tasa_Desempleo), which we analyze in detail in the final section to select our regression predictors.

6. Categorisation and Analysis by Half-Year

Transform the numerical indicators into categorical variables quarter by quarter to analyse behavioural patterns by half-year (S1 vs S2). Create half_year and year_half_year, categorise GDP (expansion vs recession, leaving 2015 as NA), categorise inflation (low, moderate, high), categorise unemployment relative to its mean and standard deviation (low, medium, high), categorise the tourist season (high, medium, low) while checking which quarter recorded the most visitors each year, count half-year category combinations with group_by() and summarise(), and construct the composite indicator clima_economico plotted as a stacked bar chart by year_half_year.

6.1 Create half_year (S1/S2) and year_half_year

  project_data <- project_data %>%
  mutate(
    Half_Year = case_when(
      Quarter == 1 | Quarter == 2 ~ "S1",
      Quarter == 3 | Quarter == 4 ~ "S2"
    ),
    Year_Half = paste0(Year, "-", Half_Year)
  )

project_data$Half_Year <- factor(project_data$Half_Year, levels = c("S1", "S2"))
project_data$Year_Half <- factor(project_data$Year_Half)

6.2 Categorise GDP based on pib_yoy (2015 remains NA)

project_data <- project_data %>%
  mutate(
    GDP_Categorical = case_when(
      pib_yoy > 0 ~ "expansion",
      pib_yoy < 0 | pib_yoy == 0 ~ "recession"
    )
  )
project_data$GDP_Categorical <- factor(project_data$GDP_Categorical, levels = c("expansion", "recession"))
print(project_data[, c("Periodo", "pib_yoy", "GDP_Categorical")])
   Periodo    pib_yoy GDP_Categorical
40  2015T1         NA            <NA>
39  2015T2         NA            <NA>
38  2015T3         NA            <NA>
37  2015T4         NA            <NA>
36  2016T1   3.673953       expansion
35  2016T2   2.864993       expansion
34  2016T3   2.735895       expansion
33  2016T4   2.405234       expansion
32  2017T1   2.418626       expansion
31  2017T2   3.148400       expansion
30  2017T3   2.985916       expansion
29  2017T4   3.027260       expansion
28  2018T1   2.740470       expansion
27  2018T2   2.340241       expansion
26  2018T3   2.265549       expansion
25  2018T4   2.241719       expansion
24  2019T1   2.430482       expansion
23  2019T2   2.060384       expansion
22  2019T3   1.688229       expansion
21  2019T4   1.673455       expansion
20  2020T1  -4.178051       recession
19  2020T2 -21.451619       recession
18  2020T3  -9.134756       recession
17  2020T4  -8.994746       recession
16  2021T1  -2.872426       recession
15  2021T2  19.765861       expansion
14  2021T3   5.370384       expansion
13  2021T4   6.736464       expansion
12  2022T1   6.885640       expansion
11  2022T2   7.258696       expansion
10  2022T3   6.083998       expansion
9   2022T4   4.565547       expansion
8   2023T1   3.873062       expansion
7   2023T2   2.363388       expansion
6   2023T3   2.164712       expansion
5   2023T4   2.331020       expansion
4   2024T1   2.724732       expansion
3   2024T2   3.262424       expansion
2   2024T3   3.309806       expansion
1   2024T4   3.299464       expansion
# Writing print(project_data) instead of print(project_data[, c("period", "pib_yoy", "GDP_categorical")]) shows the result of all columns, instead of only period, pib_yoy and GDP_categorical.

6.3 Categorise inflation (IPC_growth)

project_data <- project_data %>%
  mutate(
    Inflation_Cat = case_when(
      IPC_Variacion < 2                       ~ "low",
      IPC_Variacion >= 2 & IPC_Variacion <= 4 ~ "moderate",
      IPC_Variacion > 4                       ~ "high"
    )
  )

project_data$Inflation_Cat <- factor(project_data$Inflation_Cat, levels = c("low", "moderate", "high"))

6.4 Categorise unemployment rate using sample mean and standard deviation

m_unemp <- mean(project_data$Tasa_Desempleo, na.rm = TRUE)
s_unemp <- sd(project_data$Tasa_Desempleo, na.rm = TRUE)

project_data <- project_data %>%
  mutate(
    Unemployment_Cat = case_when(
      Tasa_Desempleo < (m_unemp - 0.5 * s_unemp) ~ "low",
      Tasa_Desempleo > (m_unemp + 0.5 * s_unemp) ~ "high",
      TRUE                                       ~ "medium"
    )
  )

project_data$Unemployment_Cat <- factor(project_data$Unemployment_Cat, levels = c("low", "medium", "high"))

6.5 Categorise tourism season and verify peak visitor quarter per year

project_data <- project_data%>%
  mutate(
    Season_Cat = case_when(
      Quarter == 3 ~ "high",
      Quarter == 2 ~ "medium",
      Quarter == 1 | Quarter == 4 ~ "low"
    )
  )

project_data$Season_Cat <- factor(project_data$Season_Cat, levels = c("low", "medium", "high"))

peak_visitors <- project_data %>%
  group_by(Year) %>%
  summarise(
    max_tourism = max(Visitantes_Totales, na.rm = TRUE),
    quarter_max = Quarter[which.max(Visitantes_Totales)], # which.max() to find in which position the max value is.
    season_max  = Season_Cat[which.max(Visitantes_Totales)]
  )

print(peak_visitors)
# A tibble: 10 × 4
    Year max_tourism quarter_max season_max
   <dbl>       <dbl>       <dbl> <fct>     
 1  2015    25340120           3 high      
 2  2016    27505870           3 high      
 3  2017    29768453           3 high      
 4  2018    29128315           3 high      
 5  2019    28836788           3 high      
 6  2020    10557630           1 low       
 7  2021    14299445           3 high      
 8  2022    25707266           3 high      
 9  2023    29098504           3 high      
10  2024    31383946           3 high      

6.6 Count how many quarters there are for each combination of categories in each half-year

project_data %>%
  filter(!is.na(GDP_Categorical)) %>%
  group_by(Half_Year, GDP_Categorical, Unemployment_Cat) %>%
  summarise(Quarters = n())
`summarise()` has regrouped the output.
ℹ Summaries were computed grouped by Half_Year, GDP_Categorical, and
  Unemployment_Cat.
ℹ Output is grouped by Half_Year and GDP_Categorical.
ℹ Use `summarise(.groups = "drop_last")` to silence this message.
ℹ Use `summarise(.by = c(Half_Year, GDP_Categorical, Unemployment_Cat))` for
  per-operation grouping (`?dplyr::dplyr_by`) instead.
# A tibble: 8 × 4
# Groups:   Half_Year, GDP_Categorical [4]
  Half_Year GDP_Categorical Unemployment_Cat Quarters
  <fct>     <fct>           <fct>               <int>
1 S1        expansion       low                     6
2 S1        expansion       medium                  5
3 S1        expansion       high                    4
4 S1        recession       medium                  3
5 S2        expansion       low                     8
6 S2        expansion       medium                  6
7 S2        expansion       high                    2
8 S2        recession       medium                  2
project_data %>%
  group_by(Half_Year, Inflation_Cat, Season_Cat) %>%
  summarise(Quarters = n())
`summarise()` has regrouped the output.
ℹ Summaries were computed grouped by Half_Year, Inflation_Cat, and Season_Cat.
ℹ Output is grouped by Half_Year and Inflation_Cat.
ℹ Use `summarise(.groups = "drop_last")` to silence this message.
ℹ Use `summarise(.by = c(Half_Year, Inflation_Cat, Season_Cat))` for
  per-operation grouping (`?dplyr::dplyr_by`) instead.
# A tibble: 7 × 4
# Groups:   Half_Year, Inflation_Cat [4]
  Half_Year Inflation_Cat Season_Cat Quarters
  <fct>     <fct>         <fct>         <int>
1 S1        low           low               9
2 S1        low           medium            7
3 S1        moderate      low               1
4 S1        moderate      medium            3
5 S2        low           low               8
6 S2        low           high             10
7 S2        moderate      low               2

6.7 Create an economic climate variable (clima_economico) and plot evolution on a bar stacked chart

project_data <- project_data %>%
  mutate(
    clima_economico = case_when(
      GDP_Categorical == "recession" ~ "unfavourable",
      Unemployment_Cat == "high" &  Inflation_Cat == "high" ~ "unfavourable",
      GDP_Categorical == "expansion" & Unemployment_Cat == "low" ~ "favourable",
      TRUE ~ "mixed"
    )
  )

project_data$clima_economico <- factor(project_data$clima_economico, levels = c("favourable", "mixed", "unfavourable"))

ggplot(filter(project_data, !is.na(GDP_Categorical)), aes(x = Year_Half, fill = clima_economico)) +
  geom_bar(color = "black") +
  labs(
    title   = "Number of Quarters Corresponding to Each Economic Climate (2016-S1 to 2024-S2)",
    x       = "Semester",
    y       = "Number of Quarters",
    fill    = "Economic Climate",
    caption = "Source: Project Data"
  ) +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

The bar chart shows how the economic climate changed each semester from 2016-S1 to 2024-S2, reflecting how industrial production, the labor market and external shocks shaped the economy. From 2016-S1 to 2019-S1, every quarter remained mixed due to gradual post-2008 recovery with moderate growth and elevated unemployment. In 2020-S1 and 2020-S2, all four quarters turned unfavourable due to COVID-19 lockdowns, collapsing tourism and a sharp drop in industrial activity and employment. As restrictions eased and vaccines were launched out in 2021, rebounding demand and hiring drove a recovery from one unfavourable and one mixed quarter in 2021-S1 to one mixed and one favourable quarter in 2021-S2. Finally, from 2022-S1 to 2024-S2, every quarter stayed favourable due to strong tourism inflows, job creation and resilient industrial and service-sector expansion.

7. Questions with dplyr

7.1 Using filter(), obtain and display the quarters in which GDP recorded a negative year-on-year change (recession quarters, pib_yoy < 0).

q1_recession <- project_data %>%
  filter(`pib_yoy` < 0)

print(q1_recession)
  Periodo PIB_Indice IPC_Variacion Tasa_Desempleo Exportacion_Millones
1  2020T1   107.1046        -1.472          14.41                84110
2  2020T2    88.0503         0.758          15.33                58420
3  2020T3   102.0523        -0.703          16.26                78115
4  2020T4   102.7928         0.904          16.13                87940
5  2021T1   104.0281         0.384          15.98                85340
  Importacion_Millones Visitantes_Totales IPI_Desestacionalizado_Medio Year
1                83990           10557630                      97.5860 2020
2                60115             204272                      77.9677 2020
3                73190            6044625                      97.2433 2020
4                81332            2126576                     100.1343 2020
5                80320            1214374                     100.1867 2021
  Quarter    pib_yoy Half_Year Year_Half GDP_Categorical Inflation_Cat
1       1  -4.178051        S1   2020-S1       recession           low
2       2 -21.451619        S1   2020-S1       recession           low
3       3  -9.134756        S2   2020-S2       recession           low
4       4  -8.994746        S2   2020-S2       recession           low
5       1  -2.872426        S1   2021-S1       recession           low
  Unemployment_Cat Season_Cat clima_economico
1           medium        low    unfavourable
2           medium     medium    unfavourable
3           medium       high    unfavourable
4           medium        low    unfavourable
5           medium        low    unfavourable

7.2 Using filter(), obtain and display the quarters in which year-on-year inflation (IPC_Variación) exceeded 3% (IPC_Variación > 3, in percentage points).

q2_high_inflation <- project_data %>%
  filter(IPC_Variacion > 3)

print(q2_high_inflation)
  Periodo PIB_Indice IPC_Variacion Tasa_Desempleo Exportacion_Millones
1  2021T4   109.7174         3.371          13.33               108971
2  2022T1   111.1911         3.464          13.65               114731
  Importacion_Millones Visitantes_Totales IPI_Desestacionalizado_Medio Year
1               101442           11458258                     101.8120 2021
2               112981            9720263                     101.1687 2022
  Quarter  pib_yoy Half_Year Year_Half GDP_Categorical Inflation_Cat
1       4 6.736464        S2   2021-S2       expansion      moderate
2       1 6.885640        S1   2022-S1       expansion      moderate
  Unemployment_Cat Season_Cat clima_economico
1              low        low      favourable
2              low        low      favourable

7.3 Using filter() and select(), display only the period and the number of visitors in the high-season quarters (T3).

q3_high_season <- project_data %>%
  filter(Quarter == 3) %>%
  select(Periodo, Visitantes_Totales)

print(q3_high_season)
   Periodo Visitantes_Totales
1   2015T3           25340120
2   2016T3           27505870
3   2017T3           29768453
4   2018T3           29128315
5   2019T3           28836788
6   2020T3            6044625
7   2021T3           14299445
8   2022T3           25707266
9   2023T3           29098504
10  2024T3           31383946

7.4 Using group_by() and summarise(), calculate the annual mean (grouping by year, not by quarter) of the industrial production index

q4_annual_ipi <- project_data %>%
  group_by(Year) %>%
  summarise(Mean_IPI = mean(IPI_Desestacionalizado_Medio, na.rm = TRUE))

print(q4_annual_ipi)
# A tibble: 10 × 2
    Year Mean_IPI
   <dbl>    <dbl>
 1  2015     96.9
 2  2016     98.7
 3  2017    102. 
 4  2018    102. 
 5  2019    103. 
 6  2020     93.2
 7  2021    100.0
 8  2022    102. 
 9  2023    101. 
10  2024    101. 

7.5 Using mutate(), group_by() and summarise(), calculate the trade balance for each quarter (Exportacion_Millones − Importacion_Millones) and its mean per year, and use arrange() to display the years sorted from highest to lowest balance

q5_trade_balance <- project_data %>%
  mutate(Trade_Balance = Exportacion_Millones - Importacion_Millones) %>%
  group_by(Year) %>%
  summarise(Mean_Trade_Balance = mean(Trade_Balance, na.rm = TRUE)) %>%
  arrange(desc(Mean_Trade_Balance))

print(q5_trade_balance)
# A tibble: 10 × 2
    Year Mean_Trade_Balance
   <dbl>              <dbl>
 1  2023             12140.
 2  2024             10488.
 3  2016              9483.
 4  2017              8949 
 5  2015              8037 
 6  2018              6631.
 7  2021              6457.
 8  2019              5600.
 9  2022              3887.
10  2020              2490.

8. Predictive model

8.a: Define pib_yoy as the target variable and prepare the explanatory variables (ipi_yoy, trade_balance) by combining train and test data

summary(train_data$pib_yoy)
    Min.  1st Qu.   Median     Mean  3rd Qu.     Max.      NAs 
-21.4516  -0.4812   2.2983   1.1166   3.4008  19.7659        4 

8.b: Separate the training and test data, and select the last four quarters of the train dataframe

# We create a function that will calculate the trade balance (EXPORTS - IMPORTS)

tradeb <- function(x, y) {
  return(x - y)
}

# We compute the ipi year-on-year percentage growth rate to match the units for pib_yoy; economically, quarterly GDP growth accelerates when industrial production accelerates

train_temp <- train_data %>%
  mutate(
    ipi_yoy       = yoy_variation(IPI_Desestacionalizado_Medio),
    trade_balance = tradeb(Exportacion_Millones, Importacion_Millones)
  ) %>%
  na.omit()

# Fit candidate models to inspect coefficients, p-values and Adjusted R-squared

m1_full <- lm(pib_yoy ~ ipi_yoy + Tasa_Desempleo, data = train_temp)
m2_full <- lm(pib_yoy ~ trade_balance + IPI_Desestacionalizado_Medio + Visitantes_Totales + IPC_Variacion, data = train_temp)

summary(m1_full)

Call:
lm(formula = pib_yoy ~ ipi_yoy + Tasa_Desempleo, data = train_temp)

Residuals:
    Min      1Q  Median      3Q     Max 
-9.0310 -0.8984  0.3417  1.5169  4.0905 

Coefficients:
               Estimate Std. Error t value Pr(>|t|)    
(Intercept)     5.29331    0.89854   5.891 1.09e-07 ***
ipi_yoy         0.64043    0.04522  14.162  < 2e-16 ***
Tasa_Desempleo -0.22900    0.05114  -4.478 2.73e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.392 on 73 degrees of freedom
Multiple R-squared:  0.762, Adjusted R-squared:  0.7554 
F-statistic: 116.8 on 2 and 73 DF,  p-value: < 2.2e-16
summary(m2_full)

Call:
lm(formula = pib_yoy ~ trade_balance + IPI_Desestacionalizado_Medio + 
    Visitantes_Totales + IPC_Variacion, data = train_temp)

Residuals:
     Min       1Q   Median       3Q      Max 
-10.6806  -1.4358   0.0169   1.7609  17.1304 

Coefficients:
                               Estimate Std. Error t value Pr(>|t|)    
(Intercept)                  -4.414e+01  6.436e+00  -6.857 2.14e-09 ***
trade_balance                 4.221e-04  8.302e-05   5.084 2.88e-06 ***
IPI_Desestacionalizado_Medio  4.231e-01  6.590e-02   6.420 1.34e-08 ***
Visitantes_Totales            4.336e-08  6.926e-08   0.626   0.5332    
IPC_Variacion                 6.402e-01  2.989e-01   2.142   0.0356 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.641 on 71 degrees of freedom
Multiple R-squared:  0.4635,    Adjusted R-squared:  0.4333 
F-statistic: 15.34 on 4 and 71 DF,  p-value: 4.376e-09

8.c: Create two sets of combinations to select the most precise model and compare them using the validation RMSE

# We now compute ipi_yoy for the test data (the one the model has not seen yet)

full_df <- bind_rows(train_data, test_data) %>%
  mutate(
    ipi_yoy       = yoy_variation(IPI_Desestacionalizado_Medio),
    trade_balance = tradeb(Exportacion_Millones, Importacion_Millones)
  )

# Recover the last 4 blind test rows with their calculated ipi_yoy intact for prediction

train_clean <- na.omit(full_df)
test_clean  <- tail(full_df, nrow(test_data))

sub_train <- head(train_clean, -4)
val_set   <- tail(train_clean, 4)

m1 <- lm(pib_yoy ~ ipi_yoy + Tasa_Desempleo, data = sub_train)
m2 <- lm(pib_yoy ~ trade_balance + IPI_Desestacionalizado_Medio + Visitantes_Totales + IPC_Variacion, data = sub_train)

summary(m2)

Call:
lm(formula = pib_yoy ~ trade_balance + IPI_Desestacionalizado_Medio + 
    Visitantes_Totales + IPC_Variacion, data = sub_train)

Residuals:
     Min       1Q   Median       3Q      Max 
-10.9424  -1.5083   0.1221   1.7571  16.8134 

Coefficients:
                               Estimate Std. Error t value Pr(>|t|)    
(Intercept)                  -4.564e+01  6.719e+00  -6.793 3.55e-09 ***
trade_balance                 4.517e-04  8.902e-05   5.074 3.31e-06 ***
IPI_Desestacionalizado_Medio  4.386e-01  6.880e-02   6.375 1.96e-08 ***
Visitantes_Totales            3.803e-08  7.359e-08   0.517   0.6071    
IPC_Variacion                 6.734e-01  3.089e-01   2.180   0.0328 *  
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 3.715 on 67 degrees of freedom
Multiple R-squared:  0.4674,    Adjusted R-squared:  0.4356 
F-statistic:  14.7 on 4 and 67 DF,  p-value: 1.139e-08
rmse1 <- sqrt(mean((val_set$pib_yoy - predict(m1, newdata = val_set))^2))
rmse2 <- sqrt(mean((val_set$pib_yoy - predict(m2, newdata = val_set))^2))

cat("Validation RMSE Model 1:", rmse1, "\n")
Validation RMSE Model 1: 0.5296005 
cat("Validation RMSE Model 2:", rmse2, "\n")
Validation RMSE Model 2: 2.155455 

8.d: Justification on the choice of variables (heatmap, economic reasoning, significance and adjusted R², validation RMSE) and interpretation of summary(lm).

8.e: Predict pib_yoy on the test data, present the results in a table and save them in predictions_GroupX.csv.

JUSTIFICATION:

Variables chosen: Industrial Production Index growth rate and Unemployment Rate, measured in percentages.

The justification is based on both economic reasoning and the indicators we have developed throughout the project, including the correlation heatmap, the coefficients and data obtained with summary(lm) and finally the validation RMSE.

  1. Correlation heatmap

In order to select the variables that would predict GDP as precisely as possible, we first analysed the heatmap created in section 5, focusing on the pib_yoy row, since it is the variable we want to predict. The variable with the strongest relationship with GDP growth was IPI (0.67), followed by exports (0.46) and imports (0.44). These were the first variables we considered using, since the heatmap shows that when one of them changes, GDP growth is also likely to change. Tourism (0.33) and inflation (0.28) showed weaker positive relationships. The unemployment rate had the weakest correlation (−0.13), but it has an inverse sign: when unemployment increases, GDP growth tends to decline. Even though this correlation is low, we kept unemployment as a candidate, because the heatmap is only the starting point of the selection. Its economic logic (explained below) and its significance in the model, together with the adjusted R² and the validation RMSE, supported including it. Finally, exports and imports are almost perfectly correlated with each other (0.99), which means they move together. Because of this, adding both variables would be useless, as one would just repeat the same information as the other.

  1. Sign and magnitude of the coefficients:

ipi_yoy (+0.640): holding unemployment constant, a 1-point increase in the year-on-year growth of industrial production is associated with a 0.64-point increase in GDP year-on-year growth. The sign is positive, since more industrial output means more activity.

Tasa_Desempleo (−0.229): holding industrial production constant, a 1-point increase in the unemployment rate is associated with a 0.23-point decrease in GDP year-on-year growth. The sign is negative, because higher unemployment reflects weaker demand and lower production.

Intercept (5.29): constant term of the regression equation, equal to the value predicted by the model when both ipi_yoy and the unemployment rate are zero. Since an unemployment rate of 0% is not observed in the data, the intercept is not interpreted economically. It only sets the starting level of the regression line.

p-values. Both variables are significant at the 5% level: ipi_yoy (p < 0.001) and Tasa_Desempleo (p < 0.001). We therefore reject the null hypothesis that each coefficient is zero. R² and adjusted R². R² = 0.762 and adjusted R² = 0.755. The model explains about 76% of the variation in GDP year-on-year growth. The adjusted R² is almost equal to R², which indicates that the model does not include unnecessary variables.

Residual standard error. 2.392 percentage points (73 degrees of freedom). This measures the typical size of the model’s errors, that is the typical difference between the observed and the fitted GDP year-on-year growth. It is inflated by the COVID quarters (2020T2 to 2021T1), where the model’s errors are the largest, because GDP fell far more than the model predicts.

  1. Validation RMSE:

To see how accurately each model predicts new data, we tested both on the last 4 quarters of the training set (val_set) after training them on the earlier quarters (sub_train). Model 1 (pib_yoy ~ ipi_yoy + Tasa_Desempleo) achieved a validation RMSE of 0.530 percentage points, whereas Model 2 (trade_balance + IPI_Desestacionalizado_Medio + Visitantes_Totales + IPC_Variacion) had an RMSE of 2.155 percentage points. This means Model 1’s typical prediction error on unseen quarters is about four times smaller than Model 2’s. Even though Model 2 uses more variables, relying on raw levels instead of year-on-year growth makes its forecasts much less accurate. Because Model 1 predicts future quarters far more reliably, we chose it as our final model and refitted it on the entire training dataset to forecast test_data and run the scenario simulations.

# Refit winning model (Model 1) on ALL of train_clean

final_model <- lm(pib_yoy ~ ipi_yoy + Tasa_Desempleo, data = train_clean)
summary(final_model)

Call:
lm(formula = pib_yoy ~ ipi_yoy + Tasa_Desempleo, data = train_clean)

Residuals:
    Min      1Q  Median      3Q     Max 
-9.0310 -0.8984  0.3417  1.5169  4.0905 

Coefficients:
               Estimate Std. Error t value Pr(>|t|)    
(Intercept)     5.29331    0.89854   5.891 1.09e-07 ***
ipi_yoy         0.64043    0.04522  14.162  < 2e-16 ***
Tasa_Desempleo -0.22900    0.05114  -4.478 2.73e-05 ***
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 2.392 on 73 degrees of freedom
Multiple R-squared:  0.762, Adjusted R-squared:  0.7554 
F-statistic: 116.8 on 2 and 73 DF,  p-value: < 2.2e-16
test_clean$Prediction <- predict(final_model, newdata = test_clean)
print(test_clean[, c("Periodo", "Prediction")])
   Periodo Prediction
81  2025T1   2.226509
82  2025T2   3.931990
83  2025T3   3.495251
84  2025T4   3.340727
85  2026T1   3.126337

8.f: Create a baseline, optimistic and pessimistic scenario, predict GDP for each one and interpret the results economically.

last <- tail(test_clean, 1)

scenarios <- data.frame(
  Scenario       = c("Baseline", "Optimistic", "Pessimistic"),
  ipi_yoy        = c(last$ipi_yoy,        last$ipi_yoy + 3.0,        last$ipi_yoy - 5.0),
  Tasa_Desempleo = c(last$Tasa_Desempleo, last$Tasa_Desempleo - 2.0, last$Tasa_Desempleo + 3.0)
)

scenarios$pib_yoy_predicted <- predict(final_model, newdata = scenarios)

print(scenarios)
     Scenario    ipi_yoy Tasa_Desempleo pib_yoy_predicted
1    Baseline  0.4245853          10.65         3.1263369
2  Optimistic  3.4245853           8.65         5.5056370
3 Pessimistic -4.5754147          13.65        -0.7628285

knitr::opts_chunk$set( echo = TRUE, comment = NA )