Inicialmente, vamos a instalar todas las librerias necesarias para desarrollar el ejercicio. Una vez cargadas todas las librerias, procedemos a ejecutar el siguiente código
library(readr)
library(dplyr)
##
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
##
## filter, lag
## The following objects are masked from 'package:base':
##
## intersect, setdiff, setequal, union
# URL del conjunto de datos
us_population_url <- 'https://raw.githubusercontent.com/lihkir/Uninorte/main/AppliedStatisticMS/DataVisualizationRPython/Lectures/Python/PythonDataSets/us_state_population.tsv'
# Lee el conjunto de datos desde la URL
US <- read_tsv(us_population_url)
## Rows: 51 Columns: 11
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: "\t"
## chr (2): State, Code
## dbl (9): 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018
##
## ℹ 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.
head(US)
## # A tibble: 6 × 11
## State Code `2010` `2011` `2012` `2013` `2014` `2015` `2016` `2017` `2018`
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Alabama AL 4.79e6 4.80e6 4.82e6 4.83e6 4.84e6 4.85e6 4.86e6 4.88e6 4.89e6
## 2 Alaska AK 7.14e5 7.22e5 7.30e5 7.37e5 7.36e5 7.38e5 7.42e5 7.40e5 7.37e5
## 3 Arizona AZ 6.41e6 6.47e6 6.56e6 6.63e6 6.73e6 6.83e6 6.95e6 7.05e6 7.17e6
## 4 Arkansas AR 2.92e6 2.94e6 2.95e6 2.96e6 2.97e6 2.98e6 2.99e6 3.00e6 3.01e6
## 5 Californ… CA 3.73e7 3.76e7 3.80e7 3.83e7 3.86e7 3.90e7 3.92e7 3.94e7 3.96e7
## 6 Colorado CO 5.05e6 5.12e6 5.19e6 5.27e6 5.35e6 5.45e6 5.54e6 5.62e6 5.70e6
library(tidyr)
US2 = gather(US,
"2010", "2011", "2012", "2013", "2014", "2015", "2016", "2017", "2018",
key = "Year",
value = "Population")
knitr::kable(head(US2,70))
| State | Code | Year | Population |
|---|---|---|---|
| Alabama | AL | 2010 | 4785448 |
| Alaska | AK | 2010 | 713906 |
| Arizona | AZ | 2010 | 6407774 |
| Arkansas | AR | 2010 | 2921978 |
| California | CA | 2010 | 37320903 |
| Colorado | CO | 2010 | 5048281 |
| Connecticut | CT | 2010 | 3579125 |
| Delaware | DE | 2010 | 899595 |
| District of Columbia | DC | 2010 | 605085 |
| Florida | FL | 2010 | 18845785 |
| Georgia | GA | 2010 | 9711810 |
| Hawaii | HI | 2010 | 1363963 |
| Idaho | ID | 2010 | 1570773 |
| Illinois | IL | 2010 | 12840762 |
| Indiana | IN | 2010 | 6490436 |
| Iowa | IA | 2010 | 3050767 |
| Kansas | KS | 2010 | 2858213 |
| Kentucky | KY | 2010 | 4348200 |
| Louisiana | LA | 2010 | 4544532 |
| Maine | ME | 2010 | 1327632 |
| Maryland | MD | 2010 | 5788642 |
| Massachusetts | MA | 2010 | 6566431 |
| Michigan | MI | 2010 | 9877535 |
| Minnesota | MN | 2010 | 5310843 |
| Mississippi | MS | 2010 | 2970536 |
| Missouri | MO | 2010 | 5995976 |
| Montana | MT | 2010 | 990722 |
| Nebraska | NE | 2010 | 1829536 |
| Nevada | NV | 2010 | 2702464 |
| New Hampshire | NH | 2010 | 1316777 |
| New Jersey | NJ | 2010 | 8799624 |
| New Mexico | NM | 2010 | 2064588 |
| New York | NY | 2010 | 19400080 |
| North Carolina | NC | 2010 | 9574293 |
| North Dakota | ND | 2010 | 674710 |
| Ohio | OH | 2010 | 11539327 |
| Oklahoma | OK | 2010 | 3759632 |
| Oregon | OR | 2010 | 3837532 |
| Pennsylvania | PA | 2010 | 12711158 |
| Rhode Island | RI | 2010 | 1053938 |
| South Carolina | SC | 2010 | 4635656 |
| South Dakota | SD | 2010 | 816165 |
| Tennessee | TN | 2010 | 6355301 |
| Texas | TX | 2010 | 25242679 |
| Utah | UT | 2010 | 2775334 |
| Vermont | VT | 2010 | 625880 |
| Virginia | VA | 2010 | 8023680 |
| Washington | WA | 2010 | 6742902 |
| West Virginia | WV | 2010 | 1854214 |
| Wisconsin | WI | 2010 | 5690479 |
| Wyoming | WY | 2010 | 564483 |
| Alabama | AL | 2011 | 4798834 |
| Alaska | AK | 2011 | 722038 |
| Arizona | AZ | 2011 | 6473497 |
| Arkansas | AR | 2011 | 2940407 |
| California | CA | 2011 | 37641823 |
| Colorado | CO | 2011 | 5121771 |
| Connecticut | CT | 2011 | 3588023 |
| Delaware | DE | 2011 | 907316 |
| District of Columbia | DC | 2011 | 619602 |
| Florida | FL | 2011 | 19093352 |
| Georgia | GA | 2011 | 9801578 |
| Hawaii | HI | 2011 | 1379252 |
| Idaho | ID | 2011 | 1583828 |
| Illinois | IL | 2011 | 12867291 |
| Indiana | IN | 2011 | 6516045 |
| Iowa | IA | 2011 | 3066054 |
| Kansas | KS | 2011 | 2869035 |
| Kentucky | KY | 2011 | 4369488 |
| Louisiana | LA | 2011 | 4575184 |
Con este código logramos tener en un nuevo data frame (US2) con las nuevas columnas “Year” y “Population”.
Vamos a unir en una sola columna State y Code, para eso usamos el siguiente código
US3 = unite(US2, State_Code, State, Code)
knitr::kable(head(US3, 70))
| State_Code | Year | Population |
|---|---|---|
| Alabama_AL | 2010 | 4785448 |
| Alaska_AK | 2010 | 713906 |
| Arizona_AZ | 2010 | 6407774 |
| Arkansas_AR | 2010 | 2921978 |
| California_CA | 2010 | 37320903 |
| Colorado_CO | 2010 | 5048281 |
| Connecticut_CT | 2010 | 3579125 |
| Delaware_DE | 2010 | 899595 |
| District of Columbia_DC | 2010 | 605085 |
| Florida_FL | 2010 | 18845785 |
| Georgia_GA | 2010 | 9711810 |
| Hawaii_HI | 2010 | 1363963 |
| Idaho_ID | 2010 | 1570773 |
| Illinois_IL | 2010 | 12840762 |
| Indiana_IN | 2010 | 6490436 |
| Iowa_IA | 2010 | 3050767 |
| Kansas_KS | 2010 | 2858213 |
| Kentucky_KY | 2010 | 4348200 |
| Louisiana_LA | 2010 | 4544532 |
| Maine_ME | 2010 | 1327632 |
| Maryland_MD | 2010 | 5788642 |
| Massachusetts_MA | 2010 | 6566431 |
| Michigan_MI | 2010 | 9877535 |
| Minnesota_MN | 2010 | 5310843 |
| Mississippi_MS | 2010 | 2970536 |
| Missouri_MO | 2010 | 5995976 |
| Montana_MT | 2010 | 990722 |
| Nebraska_NE | 2010 | 1829536 |
| Nevada_NV | 2010 | 2702464 |
| New Hampshire_NH | 2010 | 1316777 |
| New Jersey_NJ | 2010 | 8799624 |
| New Mexico_NM | 2010 | 2064588 |
| New York_NY | 2010 | 19400080 |
| North Carolina_NC | 2010 | 9574293 |
| North Dakota_ND | 2010 | 674710 |
| Ohio_OH | 2010 | 11539327 |
| Oklahoma_OK | 2010 | 3759632 |
| Oregon_OR | 2010 | 3837532 |
| Pennsylvania_PA | 2010 | 12711158 |
| Rhode Island_RI | 2010 | 1053938 |
| South Carolina_SC | 2010 | 4635656 |
| South Dakota_SD | 2010 | 816165 |
| Tennessee_TN | 2010 | 6355301 |
| Texas_TX | 2010 | 25242679 |
| Utah_UT | 2010 | 2775334 |
| Vermont_VT | 2010 | 625880 |
| Virginia_VA | 2010 | 8023680 |
| Washington_WA | 2010 | 6742902 |
| West Virginia_WV | 2010 | 1854214 |
| Wisconsin_WI | 2010 | 5690479 |
| Wyoming_WY | 2010 | 564483 |
| Alabama_AL | 2011 | 4798834 |
| Alaska_AK | 2011 | 722038 |
| Arizona_AZ | 2011 | 6473497 |
| Arkansas_AR | 2011 | 2940407 |
| California_CA | 2011 | 37641823 |
| Colorado_CO | 2011 | 5121771 |
| Connecticut_CT | 2011 | 3588023 |
| Delaware_DE | 2011 | 907316 |
| District of Columbia_DC | 2011 | 619602 |
| Florida_FL | 2011 | 19093352 |
| Georgia_GA | 2011 | 9801578 |
| Hawaii_HI | 2011 | 1379252 |
| Idaho_ID | 2011 | 1583828 |
| Illinois_IL | 2011 | 12867291 |
| Indiana_IN | 2011 | 6516045 |
| Iowa_IA | 2011 | 3066054 |
| Kansas_KS | 2011 | 2869035 |
| Kentucky_KY | 2011 | 4369488 |
| Louisiana_LA | 2011 | 4575184 |
Vamos a separar nuevamente las columnas
US4 = separate(US3, "State_Code",into = c("State", "Code"),sep = "_")
knitr::kable(head(US4, 70))
| State | Code | Year | Population |
|---|---|---|---|
| Alabama | AL | 2010 | 4785448 |
| Alaska | AK | 2010 | 713906 |
| Arizona | AZ | 2010 | 6407774 |
| Arkansas | AR | 2010 | 2921978 |
| California | CA | 2010 | 37320903 |
| Colorado | CO | 2010 | 5048281 |
| Connecticut | CT | 2010 | 3579125 |
| Delaware | DE | 2010 | 899595 |
| District of Columbia | DC | 2010 | 605085 |
| Florida | FL | 2010 | 18845785 |
| Georgia | GA | 2010 | 9711810 |
| Hawaii | HI | 2010 | 1363963 |
| Idaho | ID | 2010 | 1570773 |
| Illinois | IL | 2010 | 12840762 |
| Indiana | IN | 2010 | 6490436 |
| Iowa | IA | 2010 | 3050767 |
| Kansas | KS | 2010 | 2858213 |
| Kentucky | KY | 2010 | 4348200 |
| Louisiana | LA | 2010 | 4544532 |
| Maine | ME | 2010 | 1327632 |
| Maryland | MD | 2010 | 5788642 |
| Massachusetts | MA | 2010 | 6566431 |
| Michigan | MI | 2010 | 9877535 |
| Minnesota | MN | 2010 | 5310843 |
| Mississippi | MS | 2010 | 2970536 |
| Missouri | MO | 2010 | 5995976 |
| Montana | MT | 2010 | 990722 |
| Nebraska | NE | 2010 | 1829536 |
| Nevada | NV | 2010 | 2702464 |
| New Hampshire | NH | 2010 | 1316777 |
| New Jersey | NJ | 2010 | 8799624 |
| New Mexico | NM | 2010 | 2064588 |
| New York | NY | 2010 | 19400080 |
| North Carolina | NC | 2010 | 9574293 |
| North Dakota | ND | 2010 | 674710 |
| Ohio | OH | 2010 | 11539327 |
| Oklahoma | OK | 2010 | 3759632 |
| Oregon | OR | 2010 | 3837532 |
| Pennsylvania | PA | 2010 | 12711158 |
| Rhode Island | RI | 2010 | 1053938 |
| South Carolina | SC | 2010 | 4635656 |
| South Dakota | SD | 2010 | 816165 |
| Tennessee | TN | 2010 | 6355301 |
| Texas | TX | 2010 | 25242679 |
| Utah | UT | 2010 | 2775334 |
| Vermont | VT | 2010 | 625880 |
| Virginia | VA | 2010 | 8023680 |
| Washington | WA | 2010 | 6742902 |
| West Virginia | WV | 2010 | 1854214 |
| Wisconsin | WI | 2010 | 5690479 |
| Wyoming | WY | 2010 | 564483 |
| Alabama | AL | 2011 | 4798834 |
| Alaska | AK | 2011 | 722038 |
| Arizona | AZ | 2011 | 6473497 |
| Arkansas | AR | 2011 | 2940407 |
| California | CA | 2011 | 37641823 |
| Colorado | CO | 2011 | 5121771 |
| Connecticut | CT | 2011 | 3588023 |
| Delaware | DE | 2011 | 907316 |
| District of Columbia | DC | 2011 | 619602 |
| Florida | FL | 2011 | 19093352 |
| Georgia | GA | 2011 | 9801578 |
| Hawaii | HI | 2011 | 1379252 |
| Idaho | ID | 2011 | 1583828 |
| Illinois | IL | 2011 | 12867291 |
| Indiana | IN | 2011 | 6516045 |
| Iowa | IA | 2011 | 3066054 |
| Kansas | KS | 2011 | 2869035 |
| Kentucky | KY | 2011 | 4369488 |
| Louisiana | LA | 2011 | 4575184 |
Crear un nuevo dataframe que sea un subconjunto del dataframe original de dfFires. El subconjunto debe contener todos los incendios del Estado de Idaho y las columnas deben ser limitadas para que sólo estén presentes las columnas YEAR_, CAUSE y TOTALACRES. Cambie el nombre de las columnas. Agrupe los datos por CAUSE y YEAR_ y luego resuma por el total de acres quemados. Trazar los resultados.
library(readr)
dfFires <- read_csv("C:\\Users\\varga\\OneDrive\\Escritorio\\Task3\\StudyArea.csv", col_types = list(UNIT = col_character()), col_names = TRUE)
knitr::kable(head(dfFires, 5))
| FID | ORGANIZATI | UNIT | SUBUNIT | SUBUNIT2 | FIRENAME | CAUSE | YEAR_ | STARTDATED | CONTRDATED | OUTDATED | STATE | STATE_FIPS | TOTALACRES |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 0 | FWS | 81682 | USCADBR | San Diego Bay National Wildlife Refuge | PUMP HOUSE | Human | 2001 | 1/1/01 0:00 | 1/1/01 0:00 | NA | California | 6 | 0.1 |
| 1 | FWS | 81682 | USCADBR | San Diego Bay National Wildlife Refuge | I5 | Human | 2002 | 5/3/02 0:00 | 5/3/02 0:00 | NA | California | 6 | 3.0 |
| 2 | FWS | 81682 | USCADBR | San Diego Bay National Wildlife Refuge | SOUTHBAY | Human | 2002 | 6/1/02 0:00 | 6/1/02 0:00 | NA | California | 6 | 0.5 |
| 3 | FWS | 81682 | USCADBR | San Diego Bay National Wildlife Refuge | MARINA | Human | 2001 | 7/12/01 0:00 | 7/12/01 0:00 | NA | California | 6 | 0.1 |
| 4 | FWS | 81682 | USCADBR | San Diego Bay National Wildlife Refuge | HILL | Human | 1994 | 9/13/94 0:00 | 9/13/94 0:00 | NA | California | 6 | 1.0 |
# Crear un nuevo DataFrame
dfIdahoFires <- subset(dfFires, STATE == 'Idaho', select = c('YEAR_', 'CAUSE', 'TOTALACRES'))
# Muestra las primeras filas del nuevo DataFrame
head(dfIdahoFires)
## # A tibble: 6 × 3
## YEAR_ CAUSE TOTALACRES
## <dbl> <chr> <dbl>
## 1 1987 Human 5
## 2 1991 Natural 150
## 3 1991 Human 800
## 4 1990 Natural 2
## 5 1985 Human 38
## 6 1988 Human 2
# Cambiamos el nombre
colnames(dfIdahoFires) <- c('Year', 'Cause', 'TotalAcres')
# Muestra las primeras filas del nuevo DataFrame
head(dfIdahoFires)
## # A tibble: 6 × 3
## Year Cause TotalAcres
## <dbl> <chr> <dbl>
## 1 1987 Human 5
## 2 1991 Natural 150
## 3 1991 Human 800
## 4 1990 Natural 2
## 5 1985 Human 38
## 6 1988 Human 2
library(ggplot2)
# Agrupamos entonces por CAUSE y YEAR_ y sumamos el TOTALACRES
dfSummarized <- aggregate(TotalAcres ~ Cause + Year, data = dfIdahoFires, sum)
# Crear un gráfico de barras
ggplot(dfSummarized, aes(x = Year, y = TotalAcres, fill = Cause)) +
geom_bar(stat = 'identity', position = 'dodge') +
labs(title = 'Total de Acres por Causa y Año en Idaho',
x = 'Año',
y = 'Total de Acres',
fill = 'Causa') +
theme_minimal()
Inicialmente, vamos a instalar todas las librerias necesarias para desarrollar el ejercicio. Una vez cargadas todas las librerias, procedemos a ejecutar el siguiente código
library(readr)
library(dplyr)
# URL del conjunto de datos
url <- 'https://raw.githubusercontent.com/lihkirun/AppliedStatisticMS/main/DataVisualizationRPython/Lectures/Python/PythonDataSets/athlete_events.csv'
# Lee el conjunto de datos desde la URL
US <- read_csv(url)
## Rows: 271116 Columns: 15
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (10): Name, Sex, Team, NOC, Games, Season, City, Sport, Event, Medal
## dbl (5): ID, Age, Height, Weight, Year
##
## ℹ 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.
head(US)
## # A tibble: 6 × 15
## ID Name Sex Age Height Weight Team NOC Games Year Season City
## <dbl> <chr> <chr> <dbl> <dbl> <dbl> <chr> <chr> <chr> <dbl> <chr> <chr>
## 1 1 A Dijiang M 24 180 80 China CHN 1992… 1992 Summer Barc…
## 2 2 A Lamusi M 23 170 60 China CHN 2012… 2012 Summer Lond…
## 3 3 Gunnar N… M 24 NA NA Denm… DEN 1920… 1920 Summer Antw…
## 4 4 Edgar Li… M 34 NA NA Denm… DEN 1900… 1900 Summer Paris
## 5 5 Christin… F 21 185 82 Neth… NED 1988… 1988 Winter Calg…
## 6 5 Christin… F 21 185 82 Neth… NED 1988… 1988 Winter Calg…
## # ℹ 3 more variables: Sport <chr>, Event <chr>, Medal <chr>
# Colocamos solo los años que corresponden a 2016
US_2016 <- US %>% filter(Year == 2016)
# Agrupamos por deporte
medallas_por_deporte <- US_2016 %>%
group_by(Sport) %>%
summarise(Medallas = sum(!is.na(Medal)))
# Ordena por el número de medallas para poder tomar los primeros cinco
top5_deportes <- medallas_por_deporte %>%
arrange(desc(Medallas)) %>%
head(5)
# Gráfico
ggplot(top5_deportes, aes(x = reorder(Sport, -Medallas), y = Medallas, fill = Sport)) +
geom_bar(stat = "identity") +
labs(title = "Número de Medallas en los Cinco Principales Deportes en 2016",
x = "Deporte",
y = "Número de Medallas") +
theme_minimal()
2. Trace un gráfico que represente la distribución de la edad de los
ganadores de medallas en los cinco principales deportes en 2016.
# Filtrmos según el año hy las medallas
US_2016_medallas <- US %>%
filter(Year == 2016, !is.na(Medal))
# Tomamos solo los 5
top5_deportes <- US_2016_medallas %>%
group_by(Sport) %>%
summarise(Medallas = sum(!is.na(Medal))) %>%
arrange(desc(Medallas)) %>%
head(5)
# Filtra para los 5 deportes
US_2016_top5 <- US_2016_medallas %>%
filter(Sport %in% top5_deportes$Sport)
# Grafico para ver la distribución
ggplot(US_2016_top5, aes(x = Sport, y = Age, fill = Sport)) +
geom_violin() +
labs(title = "Distribución de Edad de personas con medallas en los 5 Deportes en 2016",
x = "Deporte",
y = "Edad") +
theme_minimal()
3. Descubre qué equipos nacionales ganaron el mayor número de medallas
en los cinco principales deportes en 2016.
# Filtramos para los 5 deportes
US_2016_top5 <- US_2016_medallas %>%
filter(Sport %in% top5_deportes$Sport)
# Agrupa por país y deporte, y cuenta el número de medallas
medallas_por_pais <- US_2016_top5 %>%
group_by(NOC, Sport) %>%
summarise(Total_Medallas = n(), .groups = "drop")
# Encuentra el país con el mayor número de medallas en cada deporte
top_paises_por_deporte <- medallas_por_pais %>%
group_by(Sport) %>%
filter(rank(desc(Total_Medallas)) == 1)
# Muestra los resultados
print(top_paises_por_deporte)
## # A tibble: 5 × 3
## # Groups: Sport [5]
## NOC Sport Total_Medallas
## <chr> <chr> <int>
## 1 GBR Rowing 26
## 2 GER Football 35
## 3 GER Hockey 33
## 4 USA Athletics 46
## 5 USA Swimming 71
# Filtramos para los 5 deportes
US_2016_top5 <- US_2016_medallas %>%
filter(Sport %in% top5_deportes$Sport)
# Agrupamos por país y deporte, y contamos el número de medallas
medallas_por_pais <- US_2016_top5 %>%
group_by(NOC, Sport) %>%
summarise(Total_Medallas = n(), .groups = "drop")
# Encuentra el país con el mayor número de medallas en cada deporte
top_paises_por_deporte <- medallas_por_pais %>%
group_by(Sport) %>%
filter(rank(desc(Total_Medallas)) == 1)
# Gráfico de barras
ggplot(top_paises_por_deporte, aes(x = Sport, y = Total_Medallas, fill = NOC)) +
geom_bar(stat = "identity", position = "dodge") +
labs(title = 'Países con Mayor Número de Medallas en los 5 Deportes Principales en 2016',
x = 'Deporte',
y = 'Total de Medallas') +
theme_minimal()
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats 1.0.0 ✔ stringr 1.5.0
## ✔ lubridate 1.9.3 ✔ tibble 3.2.1
## ✔ purrr 1.0.2
## ── 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
# Año 2016 y con medallas
US_2016_medallas <- US %>%
filter(Year == 2016, !is.na(Medal))
# 5 deportes
top5_deportes <- US_2016_medallas %>%
group_by(Sport) %>%
summarise(Medallas = sum(!is.na(Medal))) %>%
arrange(desc(Medallas)) %>%
head(5)
#Nos quedamos con los datos apra los cinco principales deportes
US_2016_top5 <- US_2016_medallas %>%
filter(Sport %in% top5_deportes$Sport)
# Gráfico
ggplot(US_2016_top5, aes(x = as.factor(Year), y = Weight, color = Sex)) +
geom_point(position = position_jitterdodge(jitter.width = 0.2, dodge.width = 0.8), size = 2) +
labs(title = "Tendencia del Peso de Atletas Ganadores por Género en los Cinco Principales Deportes en 2016",
x = "Año",
y = "Peso",
color = "Género") +
theme_minimal()
## Warning: Removed 5 rows containing missing values (`geom_point()`).
# Año 2016 y con medallas
US_2016_medallas <- US %>%
filter(Year == 2016, !is.na(Medal))
# 5 deportes
top5_deportes <- US_2016_medallas %>%
group_by(Sport) %>%
summarise(Medallas = sum(!is.na(Medal))) %>%
arrange(desc(Medallas)) %>%
head(5)
# Nos quedamos con los datos para los cinco principales deportes
US_2016_top5 <- US_2016_medallas %>%
filter(Sport %in% top5_deportes$Sport)
# Gráfico de barras agrupadas
ggplot(US_2016_top5, aes(x = Sport, y = Weight, fill = Sex)) +
geom_bar(stat = "identity", position = "dodge") +
labs(title = "Tendencia del Peso de Atletas Ganadores por Género en los Cinco Principales Deportes en 2016",
x = "Deporte",
y = "Peso",
fill = "Género") +
theme_minimal()
## Warning: Removed 5 rows containing missing values (`geom_bar()`).
Podemos notar que en su mayoría el genero masculino tiene un peso medio
superior al de las mujeres. Asimismo, que ahy pocos casos que se salen
de la media del grupo. Por otro lado, hay una mujer que supera todos los
pesos de los hombres.
library(readr)
library(dplyr)
# URL del conjunto de datos
Tecnoglass <-"https://raw.githubusercontent.com/lihkir/Data/main/TGLS.csv"
# Lee el conjunto de datos desde la URL
TC <- read_csv(Tecnoglass)
## Rows: 2200 Columns: 7
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl (6): Open, High, Low, Close, Adj Close, Volume
## date (1): Date
##
## ℹ 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.
head(TC,70)
## # A tibble: 70 × 7
## Date Open High Low Close `Adj Close` Volume
## <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 2012-05-10 9.97 10 9.5 9.8 7.95 6900
## 2 2012-05-11 9.7 9.7 9.7 9.7 7.86 300
## 3 2012-05-14 9.8 9.8 9.8 9.8 7.95 100
## 4 2012-05-15 9.75 9.75 9.75 9.75 7.91 300
## 5 2012-05-16 9.75 9.75 9.75 9.75 7.91 0
## 6 2012-05-17 9.6 9.6 9.6 9.6 7.78 800
## 7 2012-05-18 9.6 9.6 9.6 9.6 7.78 0
## 8 2012-05-21 9.6 9.6 9.6 9.6 7.78 0
## 9 2012-05-22 9.69 9.69 9.69 9.69 7.86 1500
## 10 2012-05-23 9.77 9.77 9.6 9.6 7.78 153600
## # ℹ 60 more rows
Se muestra los datos
TC <- mutate(TC, Date = as.Date(Date, format = "%Y-%m-%d"))
head(TC)
## # A tibble: 6 × 7
## Date Open High Low Close `Adj Close` Volume
## <date> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 2012-05-10 9.97 10 9.5 9.8 7.95 6900
## 2 2012-05-11 9.7 9.7 9.7 9.7 7.86 300
## 3 2012-05-14 9.8 9.8 9.8 9.8 7.95 100
## 4 2012-05-15 9.75 9.75 9.75 9.75 7.91 300
## 5 2012-05-16 9.75 9.75 9.75 9.75 7.91 0
## 6 2012-05-17 9.6 9.6 9.6 9.6 7.78 800
library(ggplot2)
# Figura
plt <- ggplot(data = TC, aes(x = Date, y = Close)) +
geom_line() +
theme_minimal() +
theme(axis.text.x = element_text(angle = 50, hjust = 1)) +
scale_x_date(date_labels = "%Y-%m-%d", date_breaks = "1 year") +
labs(title = "Gráfico de Línea de TC", x = "Fecha", y = "Cierre")
# Mostrar el gráfico
print(plt)
En este gráfico se evidencia el comportamiento de los datos, es decir,
la serie que estamos estudiando
# Histograma
hist(TC$Close, main = "Histograma", col = "lightblue", xlab = "Valor", ylab = "Frecuencia")
library(plotly)
##
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
##
## last_plot
## The following object is masked from 'package:stats':
##
## filter
## The following object is masked from 'package:graphics':
##
## layout
# Crear el gráfico de velas
fig <- plot_ly(TC, type = "candlestick",
x = ~Date,
open = ~Open,
close = ~Close,
high = ~High,
low = ~Low)
# Configurar el diseño del gráfico
fig <- fig %>%
layout(title = "Tecnoglass (TC)",
xaxis = list(title = "Day"),
yaxis = list(title = "TC-USD"),
font = list(family = "Courier New, monospace", size = 12, color = "RebeccaPurple"),
xaxis_rangeslider = list(visible = FALSE))
# Mostrar el gráfico
fig
## Warning: 'layout' objects don't have these attributes: 'xaxis_rangeslider'
## Valid attributes include:
## '_deprecated', 'activeshape', 'annotations', 'autosize', 'autotypenumbers', 'calendar', 'clickmode', 'coloraxis', 'colorscale', 'colorway', 'computed', 'datarevision', 'dragmode', 'editrevision', 'editType', 'font', 'geo', 'grid', 'height', 'hidesources', 'hoverdistance', 'hoverlabel', 'hovermode', 'images', 'legend', 'mapbox', 'margin', 'meta', 'metasrc', 'modebar', 'newshape', 'paper_bgcolor', 'plot_bgcolor', 'polar', 'scene', 'selectdirection', 'selectionrevision', 'separators', 'shapes', 'showlegend', 'sliders', 'smith', 'spikedistance', 'template', 'ternary', 'title', 'transition', 'uirevision', 'uniformtext', 'updatemenus', 'width', 'xaxis', 'yaxis', 'barmode', 'bargap', 'mapType'
Este gráfico podemos ver gráfico de velas, donde se evidencian los precios con que abren y cierran las acciones de tecnoglass.
#Se cargan las librerias necesarias
library(tidyquant)
## Loading required package: PerformanceAnalytics
## Loading required package: xts
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
##
## ######################### Warning from 'xts' package ##########################
## # #
## # The dplyr lag() function breaks how base R's lag() function is supposed to #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or #
## # source() into this session won't work correctly. #
## # #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop #
## # dplyr from breaking base R's lag() function. #
## # #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning. #
## # #
## ###############################################################################
##
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
##
## first, last
##
## Attaching package: 'PerformanceAnalytics'
## The following object is masked from 'package:graphics':
##
## legend
## Loading required package: quantmod
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(ggplot2)
library(forecast)
library(TSA)
## Registered S3 methods overwritten by 'TSA':
## method from
## fitted.Arima forecast
## plot.Arima forecast
##
## Attaching package: 'TSA'
## The following objects are masked from 'package:PerformanceAnalytics':
##
## kurtosis, skewness
## The following object is masked from 'package:readr':
##
## spec
## The following objects are masked from 'package:stats':
##
## acf, arima
## The following object is masked from 'package:utils':
##
## tar
library(tseries)
library(uroot)
str(TC$Date) #Verificamos el tipo de dato contenido en la columna Date
## Date[1:2200], format: "2012-05-10" "2012-05-11" "2012-05-14" "2012-05-15" "2012-05-16" ...
# Crear una serie de tiempo (xts)
datos_xts <- xts(TC[, c("Open", "High", "Low", "Close", "Adj Close", "Volume")], order.by = as.Date(TC$Date))
Procedemos a graficar correlación y autocorrelación parcial
# ACF y PACF
par(mfrow=c(1,2))
acf(TC$Close)
pacf(TC$Close)
Podemos ver que el acf muestra que coreelacion entre los lags. Por el
pacf podriamos decir que hay indicios que la serie tiene un componente
AR(1)
library(TSstudio)
# Crear una serie temporal con 'Date' y 'Close'
TSserie <- ts(data = TC$Close,
start = min(TC$Date),
end = max(TC$Date),
frequency = 1)
#Creamos la serie especifica para este estudio
ts_info(TSserie) #Verficamos el contendio de la serie
## The TSserie series is a ts object with 1 variable and 3194 observations
## Frequency: 1
## Start time: 15470 1
## End time: 18663 1
# Boxplots
boxplot(TC$Close ~ format(TC$Date, "%Y"))
Esta grafica nos brinda información sobre el comportamiento de los datos
cada mes, de esta forma podemos evidenciar las diferencias entre las
medias de cada grupo.
# Prueba de Dickey-Fuller
library(urca)
adf_test <- ur.df(TSserie, type = "trend", lags = 10)
summary(adf_test)
##
## ###############################################
## # Augmented Dickey-Fuller Test Unit Root Test #
## ###############################################
##
## Test regression trend
##
##
## Call:
## lm(formula = z.diff ~ z.lag.1 + 1 + tt + z.diff.lag)
##
## Residuals:
## Min 1Q Median 3Q Max
## -1.72510 -0.06055 -0.00063 0.05016 2.63939
##
## Coefficients:
## Estimate Std. Error t value Pr(>|t|)
## (Intercept) 4.362e-02 1.891e-02 2.307 0.021124 *
## z.lag.1 -4.403e-03 1.733e-03 -2.541 0.011085 *
## tt 3.426e-07 4.062e-06 0.084 0.932799
## z.diff.lag1 -6.672e-02 1.777e-02 -3.755 0.000176 ***
## z.diff.lag2 2.423e-02 1.781e-02 1.360 0.173774
## z.diff.lag3 -2.495e-02 1.783e-02 -1.399 0.161879
## z.diff.lag4 -1.232e-02 1.783e-02 -0.691 0.489689
## z.diff.lag5 -6.076e-03 1.784e-02 -0.341 0.733479
## z.diff.lag6 3.179e-03 1.785e-02 0.178 0.858637
## z.diff.lag7 2.668e-02 1.784e-02 1.495 0.134984
## z.diff.lag8 -2.077e-03 1.784e-02 -0.116 0.907317
## z.diff.lag9 1.272e-02 1.784e-02 0.713 0.475708
## z.diff.lag10 1.963e-03 1.781e-02 0.110 0.912232
## ---
## Signif. codes: 0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
##
## Residual standard error: 0.2105 on 3170 degrees of freedom
## Multiple R-squared: 0.00938, Adjusted R-squared: 0.00563
## F-statistic: 2.501 on 12 and 3170 DF, p-value: 0.002868
##
##
## Value of test-statistic is: -2.5415 2.1693 3.2427
##
## Critical values for test statistics:
## 1pct 5pct 10pct
## tau3 -3.96 -3.41 -3.12
## phi2 6.09 4.68 4.03
## phi3 8.27 6.25 5.34
El resultado del test Dickey-Fuller (ADF) indica que la serie temporal no es estacionaria, ya que el estadístico ADF (-2.7831) está por encima de los valores críticos. El modelo ajustado, que incluye lags de la serie original, lags de la serie diferenciada y una tendencia temporal, muestra que los coeficientes asociados con el lag de la serie original y el primer lag de la serie diferenciada son estadísticamente significativos. Sin embargo, la capacidad del modelo para explicar la variabilidad de los datos es limitada, como lo indica el bajo valor del R-cuadrado ajustado (0.0052). En resumen, la serie temporal estudiada se debería hacer transformaciones adicionales.
Dado que la serie es no estacionaria, se procede a diferenciar la serie.
ts_plot(diff(TSserie, lag = 1),
title = "First Differencing",
Xtitle = "Year",
Ytitle = "Differencing TC")
La gráfica evidencia la serie diferenciada, se evidencia mayor esatbilidad a pesar de tener algunos valores sobresalientes. Para verificar la estacionariedad de esta serie diferenciadad procedemos a calcular el siguiente test
TSseriedif<-diff(TSserie)
result2 <- adf.test((TSseriedif), alternative = "stationary", k = 10)
## Warning in adf.test((TSseriedif), alternative = "stationary", k = 10): p-value
## smaller than printed p-value
print(result2)
##
## Augmented Dickey-Fuller Test
##
## data: (TSseriedif)
## Dickey-Fuller = -16.336, Lag order = 10, p-value = 0.01
## alternative hypothesis: stationary
Este test muestra una estadística de Dickey-Fuller de -16.336 con un lag order de 10 y un p-valor de 0.01. Estos resultados indican que la serie es estacionaria, respaldando la hipótesis alternativa de estacionariedad. La estadística de prueba significativamente baja y el p-valor inferior al nivel de significancia común (como 0.05) proporcionan evidencia en contra de la hipótesis nula de no estacionariedad, lo que sugiere que la diferenciación ha logrado estabilizar la serie temporal.
Dado que ya contamos con estacionariedad, procedemos con la división de datos para posteriormente entrenar el modelo y pronosticar.
#División de datos
library(TSstudio)
TC_split <- ts_split(TSserie, sample.out = 10)
train <- TC_split$train
test <- TC_split$test
Procedemos entonces a modelar a través de auto.arima usando los valores de entrenamiento
library(forecast)
TC_auto_md <- auto.arima(train)
TC_auto_md
## Series: train
## ARIMA(0,1,1)
##
## Coefficients:
## ma1
## -0.0692
## s.e. 0.0174
##
## sigma^2 = 0.0441: log likelihood = 451.64
## AIC=-899.29 AICc=-899.28 BIC=-887.15
Notamos que el ajuste proporcionado es un modelo con una diferenciacion y un modelo de medias moviles MA(1) Sin embargo, para obtener un mejor ajuste procedemos a ejecutar el siguiente código donde se realizan algunas especificaciones.
Tc_auto_md2 <- auto.arima(train,
max.order = 5,
D = 1,
d = 1,
stepwise = FALSE,
approximation = FALSE)
Tc_auto_md2
## Series: train
## ARIMA(1,1,0)
##
## Coefficients:
## ar1
## -0.0716
## s.e. 0.0177
##
## sigma^2 = 0.04409: log likelihood = 451.93
## AIC=-899.87 AICc=-899.86 BIC=-887.74
Este código nos indica que el modelo es un ARIMA (1,1,0), es decir, tenemos una diferenciacion y un autorregresivo AR(1).Asi, nos quedamos con este modelo y procedemos a evaluar con test
TC_test_fc <- forecast(Tc_auto_md2, h = 10)
TC_test_fc
## Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
## 18654 10.86504 10.59594 11.13413 10.453492 11.27658
## 18655 10.86396 10.49677 11.23114 10.302397 11.42552
## 18656 10.86404 10.41914 11.30893 10.183631 11.54444
## 18657 10.86403 10.35316 11.37490 10.082727 11.64533
## 18658 10.86403 10.29478 11.43328 9.993441 11.73462
## 18659 10.86403 10.24186 11.48621 9.912496 11.81557
## 18660 10.86403 10.19309 11.53497 9.837916 11.89015
## 18661 10.86403 10.14764 11.58042 9.768402 11.95966
## 18662 10.86403 10.10490 11.62316 9.703042 12.02502
## 18663 10.86403 10.06445 11.66362 9.641171 12.08689
accuracy(TC_test_fc, test)
## ME RMSE MAE MPE MAPE MASE
## Training set 0.0003612664 0.2099093 0.1162788 -0.03077672 1.281705 0.9983422
## Test set -0.0481249393 0.4190506 0.3840938 -0.59224199 3.559089 3.2977380
## ACF1 Theil's U
## Training set 0.001264173 NA
## Test set 0.711405513 1.61441
Este código permite visualizar métricas de evaluación del rendimiento de un modelo en dos conjuntos de datos: el conjunto de entrenamiento y el conjunto de prueba. En el conjunto de entrenamiento, el modelo muestra un error cuadrático medio relativo (RMSE) bajo de 0.2099 y un error absoluto medio (MAE) de 0.1163, lo que indica un buen ajuste a los datos de entrenamiento. Sin embargo, en el conjunto de prueba, el rendimiento del modelo disminuye (como es de esperarse), mostrando un RMSE de 0.4191 y un MAE de 0.3841.
length(test) #Nos aseguramos que tengan el mismo tamaño para poder ejecutar el siguiente codigo
## [1] 10
length(TC_test_fc)
## [1] 10
test_forecast(TSserie,
forecast.obj = TC_test_fc,
test = test)
Con este grafico, podemos evidenciar la serie original y el ajuste que tiene el modelo gráficamente con los valores de entrenamiento y de test
Dado que se han satisfecho las condiciones previas, procederemos al paso final del proceso de predicción, que consiste en generar la predicción definitiva utilizando el modelo elegido. Iniciaremos este paso volviendo a entrenar el modelo seleccionado en la totalidad de la serie.
final_md <- arima(TSserie, order = c(1,1,0))
checkresiduals(final_md)
##
## Ljung-Box test
##
## data: Residuals from ARIMA(1,1,0)
## Q* = 7.5156, df = 9, p-value = 0.5836
##
## Model df: 1. Total lags used: 10
Al examinar el gráfico de residuos previo, se nota que los residuos son similares al ruido blanco y siguen una distribución normal.A pesar de tener unos pocos datos que se salen, que incluso podrian indicar valores atipicos.
Procedemos a hacer la busqueda manual del mejor modelo ARIMA que se ajusta a la serie estudiada. Para ello ejecutamos el siguiente código. Cabe resaltar que no se incluye estacionalidad porque la serie no evidencia esta característica
# Función para encontrar los mejores parámetros ARIMA
best_ARIMA <- function(TSserie, p_n, d_n, q_n) {
best_aic <- Inf
best_pdq <- NULL
fit <- NULL
for (p in 1:p_n) {
for (d in 1:d_n) {
for (q in 1:q_n) {
tryCatch({
tmp_fit <- arima(TSserie, order = c(p, d, q), method = "CSS-ML")
tmp_aic <- AIC(tmp_fit)
if (tmp_aic < best_aic) {
best_aic <- tmp_aic
best_pdq <- c(p, d, q)
fit <- tmp_fit
}
}, error = function(e) {})
}
}
}
return(list("best_aic" = best_aic, "best_pdq" = best_pdq, "best_fit" = fit))
}
# Definir rangos de parámetros
p_range <- 3
d_range <- 3
q_range <- 3
# Encontrar los mejores parámetros
best_params <- best_ARIMA(TSserie, p_range, d_range, q_range)
# Imprimir los mejores parámetros
cat("Mejores parámetros ARIMA:", best_params$best_pdq, "\n")
## Mejores parámetros ARIMA: 1 1 1
# Imprimir el modelo ajustado con los mejores parámetros
print(best_params$best_fit)
##
## Call:
## arima(x = TSserie, order = c(p, d, q), method = "CSS-ML")
##
## Coefficients:
## ar1 ma1
## -0.4774 0.4093
## s.e. 0.1645 0.1710
##
## sigma^2 estimated as 0.04416: log likelihood = 450.26, aic = -896.52
# Utilizar los mejores parámetros encontrados
best_params <- best_ARIMA(train, p_range, d_range, q_range)
# Ajustar el modelo ARIMA al conjunto de entrenamiento con los mejores parámetros
fit_model <- arima(train, order = best_params$best_pdq)
# Imprimir el modelo ajustado
print(fit_model)
##
## Call:
## arima(x = train, order = best_params$best_pdq)
##
## Coefficients:
## ar1 ma1
## -0.4376 0.3691
## s.e. 0.1876 0.1938
##
## sigma^2 estimated as 0.04405: log likelihood = 452.93, aic = -901.87
checkresiduals(fit_model)
##
## Ljung-Box test
##
## data: Residuals from ARIMA(1,1,1)
## Q* = 5.6521, df = 8, p-value = 0.6861
##
## Model df: 2. Total lags used: 10
Los resultados obtenidos indican que se distribuyen de manera cercana a una distribución normal y, además, son independientes. Después de esto, vamos a crear un gráfico con las predicciones generadas por el modelo que hemos encontrado.
#fit_model2 <- arima(train, order = c(1,1,1))
#fit_model2
#TC_test2_fc <- forecast(fit_model2, h = 10)
#TC_test2_fc
#accuracy(fit_model2, test)
#test_forecast(TSseries,
#forecast.obj = TC_test2_fc,
#test = test)