Tarea Descomposicion

library(fma)
library(ggplot2)
library(dplyr)
library(forecast)
library(TSA)
library(tsibbledata)
global_economy
# A tibble: 15,150 × 9
   Country     Code   Year         GDP Growth   CPI Imports Exports Population
   <fct>       <fct> <dbl>       <dbl>  <dbl> <dbl>   <dbl>   <dbl>      <dbl>
 1 Afghanistan AFG    1960  537777811.     NA    NA    7.02    4.13    8996351
 2 Afghanistan AFG    1961  548888896.     NA    NA    8.10    4.45    9166764
 3 Afghanistan AFG    1962  546666678.     NA    NA    9.35    4.88    9345868
 4 Afghanistan AFG    1963  751111191.     NA    NA   16.9     9.17    9533954
 5 Afghanistan AFG    1964  800000044.     NA    NA   18.1     8.89    9731361
 6 Afghanistan AFG    1965 1006666638.     NA    NA   21.4    11.3     9938414
 7 Afghanistan AFG    1966 1399999967.     NA    NA   18.6     8.57   10152331
 8 Afghanistan AFG    1967 1673333418.     NA    NA   14.2     6.77   10372630
 9 Afghanistan AFG    1968 1373333367.     NA    NA   15.2     8.90   10604346
10 Afghanistan AFG    1969 1408888922.     NA    NA   15.0    10.1    10854428
# ℹ 15,140 more rows
data("global_economy")
global_economy %>%
  group_by(Country) %>%
  mutate(PIB_per_capita = GDP/Population) %>%
  ggplot(aes(x = Year, y = PIB_per_capita, color = Country)) +
  geom_line() +
  theme(legend.position = "none") +
  labs(x = "Año", y = "PIB per cápita", title = "Evolución del PIB per cápita por país")
Warning: Removed 3242 rows containing missing values (`geom_line()`).

data("global_economy")
data("vic_elec")

ggplot() +
  geom_line(data = subset(global_economy, Country == "USA"), aes(x = Year, y = GDP), color = "blue") +
  geom_line(data = subset(global_economy, Country == "Mexico"), aes(x = Year, y = GDP), color = "red") +
  labs(x = "Año", y = "PIB", title = "PIB de EEUU y México")

ggplot(data = vic_elec, aes(x = Date, y = Demand)) +
  geom_line() +
  labs(x = "Fecha", y = "Demanda de electricidad", title = "Demanda de electricidad en Victoria, Australia")

# Verificar los nombres de las columnas
names(plastics)
NULL
# Verificar la estructura del dataframe
str(plastics)
 Time-Series [1:60] from 1 to 5.92: 742 697 776 898 1030 ...
data("plastics")

plot(plastics, main = "Ventas mensuales del Producto A", ylab = "Ventas (miles)", xlab = "Tiempo")

decomp <- decompose(plastics)

trend <- decomp$trend
seasonal <- decomp$seasonal
random <- decomp$random

desestacionalizado <- plastics / seasonal

plot(desestacionalizado, main = "Datos desestacionalizados del Producto A", 
     ylab = "Ventas (miles)", xlab = "Tiempo")

plastics_with_outlier <- plastics
plastics_with_outlier[3] <- plastics_with_outlier[3] + 500

decomp_with_outlier <- decompose(plastics_with_outlier)
desestacionalizado_with_outlier <- plastics_with_outlier / decomp_with_outlier$seasonal

plot(desestacionalizado_with_outlier, main = "Datos desestacionalizados con outlier", 
     ylab = "Ventas (miles)", xlab = "Tiempo")