#introduccion de analisis partido palestino vs flamengo #nos da los datos y variables del partido de palestino vs flamengo lo que ocurrio en el partido

objetivo : saber cuales fueron los puntos altos dentro del juego de copa libertadores Palestino vs Flamengo

library(rvest)
library(stringr)
library(jsonlite)
library(tidyverse)
library(ggsoccer)
library(ggrepel)

# Defina o diretório onde você deseja procurar arquivos HTML
diretorio <- "~/Downloads/"
# Liste todos os arquivos com a extensão .html
arquivos_html <- list.files(path = diretorio, pattern = "\\.html$", full.names = TRUE)
# Exibir a lista de arquivos HTML
print(arquivos_html)
##  [1] "/Users/christiantabilojr/Downloads//aula-1-10.html"                                                   
##  [2] "/Users/christiantabilojr/Downloads//aula-1-11.html"                                                   
##  [3] "/Users/christiantabilojr/Downloads//aula-1-12.html"                                                   
##  [4] "/Users/christiantabilojr/Downloads//aula-1-13.html"                                                   
##  [5] "/Users/christiantabilojr/Downloads//aula-1-14.html"                                                   
##  [6] "/Users/christiantabilojr/Downloads//aula-1-15.html"                                                   
##  [7] "/Users/christiantabilojr/Downloads//aula-1-16.html"                                                   
##  [8] "/Users/christiantabilojr/Downloads//aula-1-2.html"                                                    
##  [9] "/Users/christiantabilojr/Downloads//aula-1-3.html"                                                    
## [10] "/Users/christiantabilojr/Downloads//aula-1-4.html"                                                    
## [11] "/Users/christiantabilojr/Downloads//aula-1-5.html"                                                    
## [12] "/Users/christiantabilojr/Downloads//aula-1-6.html"                                                    
## [13] "/Users/christiantabilojr/Downloads//aula-1-7.html"                                                    
## [14] "/Users/christiantabilojr/Downloads//aula-1-8.html"                                                    
## [15] "/Users/christiantabilojr/Downloads//aula-1-9.html"                                                    
## [16] "/Users/christiantabilojr/Downloads//aula-1.html"                                                      
## [17] "/Users/christiantabilojr/Downloads//En Directo Palestino 1-0 Flamengo - Copa Libertadores 2024.html"  
## [18] "/Users/christiantabilojr/Downloads//nose.html"                                                        
## [19] "/Users/christiantabilojr/Downloads//Palestino 1-0 Flamengo - Copa Libertadores 2024.html"             
## [20] "/Users/christiantabilojr/Downloads//plano-de-ensino.html"                                             
## [21] "/Users/christiantabilojr/Downloads//principais-funções-R.html"                                        
## [22] "/Users/christiantabilojr/Downloads//tra vs rsj.html"                                                  
## [23] "/Users/christiantabilojr/Downloads//Wolves 0-3 Nottingham Forest - Premier League 2024:2025 Live.html"
# Define o caminho para o arquivo HTML
html_path <- "/Users/christiantabilojr/Downloads//En Directo Palestino 1-0 Flamengo - Copa Libertadores 2024.html"
html_content <- read_html(html_path)
# Extrai o conteúdo de texto bruto do HTML
html_text <- html_content %>% html_text()
# Encontra o JSON usando regex
regex_pattern <- '(?<=require\\.config\\.params\\["args"\\].=.)[\\s\\S]*?;'
data_txt <- str_extract(html_text, regex_pattern)
# Faz substituições necessárias para parsear como JSON
data_txt <- gsub("matchId", '"matchId"', data_txt)
data_txt <- gsub("matchCentreData", '"matchCentreData"', data_txt)
data_txt <- gsub("matchCentreEventTypeJson", '"matchCentreEventTypeJson"', data_txt)
data_txt <- gsub("formationIdNameMappings", '"formationIdNameMappings"', data_txt)
# Remove o final }; e substitui por }
data_txt <- gsub("};$", '}', data_txt)
# Converte o texto JSON em um objeto R
data_list <- fromJSON(data_txt)
# Extrair os dados de eventos e jogadores
events <- data_list$matchCentreData$events
players <- data_list$matchCentreData$playerIdNameDictionary
# Converte em data frame
events_df <- as.data.frame(events)
players_df <- as.data.frame(players)
# inserir player df com nomes ao lado da coluna playerid
players_df <- stack(players)
events_df <- merge(events_df, players_df, by.x = "playerId", by.y = "ind", all.x = TRUE)
# ler o banco de dados para observar.
visitante = events_df%>%
  filter(teamId=="2354") # esto da para elegir los jugadores y las serie con el nombre del jugador sea visitante o local
#names(visitante)
EAD = visitante$type$displayName

table(EAD)
## EAD
##          Aerial    BallRecovery       BallTouch     BlockedPass            Card 
##              29              60              40               8               2 
##       Challenge           Claim       Clearance   CornerAwarded    Dispossessed 
##              15               1              23              11               8 
##             End           Error    FormationSet            Foul            Goal 
##               3               1               1              23               1 
##    Interception    KeeperPickup     MissedShots    OffsideGiven     OffsidePass 
##               7               3               4               3               3 
## OffsideProvoked            Pass           Punch            Save       SavedShot 
##               1             315               1               7               7 
##           Start SubstitutionOff  SubstitutionOn          Tackle          TakeOn 
##               2               5               5              20              13
# Asegúrate de extraer correctamente los nombres de los eventos
visitante <- visitante %>%
  mutate(displayName = unlist(type$displayName)) # Extraer nombres si es necesario

# Crear tabla resumen por jugador
summary_table <- visitante %>%
  group_by(values, displayName) %>%  # Agrupar por jugador y tipo de evento
  summarise(event_count = n(), .groups = "drop") %>%  # Contar eventos
  pivot_wider(names_from = displayName, values_from = event_count, values_fill = 0)  # Crear columnas para cada evento

# Mostrar tabla
print(summary_table)
## # A tibble: 17 × 31
##    values     BallRecovery Clearance  Foul  Pass SubstitutionOn Aerial BallTouch
##    <chr>             <int>     <int> <int> <int>          <int>  <int>     <int>
##  1 Antonio C…            1         1     1     1              1      0         0
##  2 Ariel Mar…            7         0     4    32              0      1         2
##  3 Benjamín …            4         4     1    20              0      0         4
##  4 Bryan Car…            4         1     1    22              0      0         6
##  5 Cristián …            2         5     1    42              0      5         0
##  6 César Rig…            4         1     0    34              0      0         0
##  7 Dilan Zúñ…            9         5     1    40              0      2         3
##  8 Fernando …            4         0     2     7              1      0         2
##  9 Iván Román            2         2     1    10              0      4         2
## 10 Joe Abrigo            1         0     1     4              1      0         0
## 11 Jonathan …            8         1     4    30              0      1         6
## 12 Junior Ma…            3         1     1    23              0     13         4
## 13 Michael F…            0         0     0     5              1      1         1
## 14 Misael Dá…            1         1     0    11              0      1         5
## 15 Nicolás L…            8         1     4    31              0      1         4
## 16 Pablo Pal…            2         0     1     3              1      0         1
## 17 <NA>                  0         0     0     0              0      0         0
## # ℹ 23 more variables: BlockedPass <int>, Challenge <int>, Interception <int>,
## #   MissedShots <int>, Save <int>, SavedShot <int>, SubstitutionOff <int>,
## #   Tackle <int>, Card <int>, CornerAwarded <int>, Dispossessed <int>,
## #   OffsidePass <int>, Error <int>, Claim <int>, KeeperPickup <int>,
## #   Punch <int>, OffsideProvoked <int>, TakeOn <int>, Goal <int>,
## #   OffsideGiven <int>, End <int>, FormationSet <int>, Start <int>
hist(summary_table$Aerial)

names(summary_table)
##  [1] "values"          "BallRecovery"    "Clearance"       "Foul"           
##  [5] "Pass"            "SubstitutionOn"  "Aerial"          "BallTouch"      
##  [9] "BlockedPass"     "Challenge"       "Interception"    "MissedShots"    
## [13] "Save"            "SavedShot"       "SubstitutionOff" "Tackle"         
## [17] "Card"            "CornerAwarded"   "Dispossessed"    "OffsidePass"    
## [21] "Error"           "Claim"           "KeeperPickup"    "Punch"          
## [25] "OffsideProvoked" "TakeOn"          "Goal"            "OffsideGiven"   
## [29] "End"             "FormationSet"    "Start"

Sumarry_table&Aerial es las veces que se gano el balón durante juegos aereos en ambos tiempos del partido generando mejores acciones en juego aereo para palestino

#BallRecovery es recuperación del balón y las cantidade de veces que los jugadores de palestino lo recuperaron durante los dos tiempos del juego en general se ve una recuperación regular del balón

ggplot(summary_table, aes(x = BallRecovery,
                          y =values))+
  geom_point(color="purple",
             size = 4 )+
  theme_minimal()

#interception es para saber las veces intercatuaron con el balón marca contra el rival sea en 1vs1 o con el balón dominado del rival

ggplot(summary_table, aes(x = Interception,
                          y =values))+
  geom_point(color="purple",
             size = 4 )+
             geom_text(aes(label=Interception),vjust = -1, size = 3)+
      theme_minimal()+labs(title="Palestino vs Flamengo",subtitle = "Partido Copa Libertadores",caption = "Christian Tabilo")

#Goal muestra la cantidad de goles durante los 2 tempos

ggplot(summary_table, aes(x = Goal,
                          y =values))+
  geom_point(color="purple",
             size = 4 )+
             geom_text(aes(label=Goal),vjust = -1, size = 3)+
      theme_minimal()+labs(title="Palestino vs Flamengo",subtitle = "Partido Copa Libertadores",caption = "Christian Tabilo")

#CornerAwarded es las veces de corner concedidos durante el partido en el primer y segundo tiempo

ggplot(summary_table, aes(x = CornerAwarded,
                          y =values))+
  geom_point(color="purple",
             size = 4 )+
             geom_text(aes(label=CornerAwarded),vjust = -1, size = 3)+
      theme_minimal()+labs(title="Palestino vs Flamengo",subtitle = "Partido Copa Libertadores",caption = "Christian Tabilo")

#SavedShot las veces que se intervino en jugadas de peligro del equipo rival

ggplot(summary_table, aes(x = SavedShot,
                          y =values))+
  geom_point(color="purple",
             size = 4 )+
             geom_text(aes(label=SavedShot),vjust = -1, size = 3)+
      theme_minimal()+labs(title="Palestino vs Flamengo",subtitle = "Partido Copa Libertadores",caption = "Christian Tabilo")

#Save las intercepción dentro del partido del arquero sea caida lateral , tomadas frontales.

ggplot(summary_table, aes(x = Save,
                          y =values))+
  geom_point(color="purple",
             size = 4 )+
             geom_text(aes(label=Save),vjust = -1, size = 3)+
      theme_minimal()+labs(title="Palestino vs Flamengo",subtitle = "Partido Copa Libertadores",caption = "Christian Tabilo")

#BallTouch las veces que toco el balon en general los jugadores entre ellos durante el primer y segundo tiempo

ggplot(summary_table, aes(x = BallTouch,
                          y =values))+
  geom_point(color="purple",
             size = 4 )+
             geom_text(aes(label=BallTouch),vjust = -1, size = 3)+
      theme_minimal()+labs(title="Palestino vs Flamengo",subtitle = "Partido Copa Libertadores",caption = "Christian Tabilo")

hist(summary_table$BallRecovery)

hist(summary_table$Interception)