#Cargamos las librerías

library(tm) #Minería de texto.
## Loading required package: NLP
library(wordcloud) #crea un corpus para hacer el análisis de frecuencia de palabras.
## Loading required package: RColorBrewer
library(topicmodels) #extraer información y categorizar grandes conjuntos de documentos.
library(ggplot2) # Hacer vizualizaciones con la información disponible.
## 
## Attaching package: 'ggplot2'
## The following object is masked from 'package:NLP':
## 
##     annotate
library(pdftools)#extraer el texto de los documentos en pdf y guardarlo en un Corpus.
## Using poppler version 23.04.0
library(tidytext) #permite realizar mineo de texto con el uso de herramientas tidy
library (dplyr) #contiene una colección de funciones para realizar operaciones de manipulación de datos comunes como: filtrar por fila, seleccionar columnas específicas, reordenar filas, añadir nuevas filas y agregar datos.
## 
## 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
library(syuzhet) #Librería para hacer el análisis de sentimiento.

#2018

# Ruta de la carpeta que contiene los archivos de texto
ruta_carpeta2018 <- "/Users/cienfuegos17/Documents/Universidad/5 Semestre/Ciencia de datos para la toma de decisiones II/Base milenio/2018"

# Lista para almacenar el texto de cada archivo
textosyt2018 <- character(0)

# Recorre cada archivo en la carpeta
archivosyt2018 <- list.files(ruta_carpeta2018, pattern = "\\.txt$", full.names = TRUE)
for (archivoyt2018 in archivosyt2018) {
  # Cargar el texto del archivo con codificación UTF-8
  texto_brutoyt2018 <- readLines(archivoyt2018, warn = FALSE, encoding = "UTF-8")
  
   # Convertir la codificación si es necesario
  texto_brutoyt2018 <- iconv(texto_brutoyt2018, from = "UTF-8", to = "ASCII//TRANSLIT")
  
  # Eliminar URL
  texto_limpioyt2018 <- gsub("http\\S+|www\\S+|ftp\\S+", "", texto_brutoyt2018)
  
  # Eliminar HTML
  texto_limpioyt2018 <- gsub("<.*?>", "", texto_limpioyt2018)
  
  # Eliminar signos de puntuación
  texto_limpioyt2018 <- gsub("[[:punct:]]", "", texto_limpioyt2018)
  
  # Agregar el texto limpio a la lista
  textosyt2018 <- c(textosyt2018, texto_limpioyt2018)
}

# Convertir la lista de textos en un solo texto
texto_finalyt2018 <- paste(textosyt2018, collapse = " ")

# Usa directamente el texto preprocesado
todos_los_textosyt2018 <- tolower(texto_finalyt2018[[1]])

#Año 2019

# Ruta de la carpeta que contiene los archivos de texto
ruta_carpeta2019 <- "/Users/cienfuegos17/Documents/Universidad/5 Semestre/Ciencia de datos para la toma de decisiones II/Base milenio/2019"

# Lista para almacenar el texto de cada archivo
textosyt2019 <- character(0)

# Recorre cada archivo en la carpeta
archivosyt2019 <- list.files(ruta_carpeta2019, pattern = "\\.txt$", full.names = TRUE)
for (archivoyt2019 in archivosyt2019) {
  # Cargar el texto del archivo con codificación UTF-8
  texto_brutoyt2019 <- readLines(archivoyt2019, warn = FALSE, encoding = "UTF-8")
  
   # Convertir la codificación si es necesario
  texto_brutoyt2019 <- iconv(texto_brutoyt2019, from = "UTF-8", to = "ASCII//TRANSLIT")
  
  # Eliminar URL
  texto_limpioyt2019 <- gsub("http\\S+|www\\S+|ftp\\S+", "", texto_brutoyt2019)
  
  # Eliminar HTML
  texto_limpioyt2019 <- gsub("<.*?>", "", texto_limpioyt2019)
  
  # Eliminar signos de puntuación
  texto_limpioyt2019 <- gsub("[[:punct:]]", "", texto_limpioyt2019)
  
  # Agregar el texto limpio a la lista
  textosyt2019 <- c(textosyt2019, texto_limpioyt2019)
}

# Convertir la lista de textos en un solo texto
texto_finalyt2019 <- paste(textosyt2019, collapse = " ")
todos_los_textosyt2019 <- tolower(texto_finalyt2019[[1]])

#Año 2020

# Ruta de la carpeta que contiene los archivos de texto
ruta_carpeta2020 <- "/Users/cienfuegos17/Documents/Universidad/5 Semestre/Ciencia de datos para la toma de decisiones II/Base milenio/2020"

# Lista para almacenar el texto de cada archivo
textosyt2020 <- character(0)

# Recorre cada archivo en la carpeta
archivosyt2020 <- list.files(ruta_carpeta2020, pattern = "\\.txt$", full.names = TRUE)
for (archivoyt2020 in archivosyt2020) {
  # Cargar el texto del archivo con codificación UTF-8
  texto_brutoyt2020 <- readLines(archivoyt2020, warn = FALSE, encoding = "UTF-8")
  
   # Convertir la codificación si es necesario
  texto_brutoyt2020 <- iconv(texto_brutoyt2020, from = "UTF-8", to = "ASCII//TRANSLIT")
  
  # Eliminar URL
  texto_limpioyt2020 <- gsub("http\\S+|www\\S+|ftp\\S+", "", texto_brutoyt2020)
  
  # Eliminar HTML
  texto_limpioyt2020 <- gsub("<.*?>", "", texto_limpioyt2020)
  
  # Eliminar signos de puntuación
  texto_limpioyt2020 <- gsub("[[:punct:]]", "", texto_limpioyt2020)
  
  # Agregar el texto limpio a la lista
  textosyt2020 <- c(textosyt2020, texto_limpioyt2020)
}

# Convertir la lista de textos en un solo texto
texto_finalyt2020 <- paste(textosyt2020, collapse = " ")

# Usa directamente el texto preprocesado
todos_los_textosyt2020 <- tolower(texto_finalyt2020[[1]])

#2021

# Ruta de la carpeta que contiene los archivos de texto
ruta_carpeta2021 <- "/Users/cienfuegos17/Documents/Universidad/5 Semestre/Ciencia de datos para la toma de decisiones II/Base milenio/2021"

# Lista para almacenar el texto de cada archivo
textosyt2021 <- character(0)

# Recorre cada archivo en la carpeta
archivosyt2021 <- list.files(ruta_carpeta2021, pattern = "\\.txt$", full.names = TRUE)
for (archivoyt2021 in archivosyt2021) {
  # Cargar el texto del archivo con codificación UTF-8
  texto_brutoyt2021 <- readLines(archivoyt2021, warn = FALSE, encoding = "UTF-8")
  
   # Convertir la codificación si es necesario
  texto_brutoyt2021 <- iconv(texto_brutoyt2021, from = "UTF-8", to = "ASCII//TRANSLIT")
  
  # Eliminar URL
  texto_limpioyt2021 <- gsub("http\\S+|www\\S+|ftp\\S+", "", texto_brutoyt2021)
  
  # Eliminar HTML
  texto_limpioyt2021 <- gsub("<.*?>", "", texto_limpioyt2021)
  
  # Eliminar signos de puntuación
  texto_limpioyt2021 <- gsub("[[:punct:]]", "", texto_limpioyt2021)
  
  # Agregar el texto limpio a la lista
  textosyt2021 <- c(textosyt2021, texto_limpioyt2021)
}

# Convertir la lista de textos en un solo texto
texto_finalyt2021 <- paste(textosyt2021, collapse = " ")
todos_los_textosyt2021 <- tolower(texto_finalyt2021[[1]])

#Año 2022

# Ruta de la carpeta que contiene los archivos de texto
ruta_carpeta2022 <- "/Users/cienfuegos17/Documents/Universidad/5 Semestre/Ciencia de datos para la toma de decisiones II/Base milenio/2022"

# Lista para almacenar el texto de cada archivo
textosyt2022 <- character(0)

# Recorre cada archivo en la carpeta
archivosyt2022 <- list.files(ruta_carpeta2022, pattern = "\\.txt$", full.names = TRUE)
for (archivoyt2022 in archivosyt2022) {
  # Cargar el texto del archivo con codificación UTF-8
  texto_brutoyt2022 <- readLines(archivoyt2022, warn = FALSE, encoding = "UTF-8")
  
   # Convertir la codificación si es necesario
  texto_brutoyt2022 <- iconv(texto_brutoyt2022, from = "UTF-8", to = "ASCII//TRANSLIT")
  
  # Eliminar URL
  texto_limpioyt2022 <- gsub("http\\S+|www\\S+|ftp\\S+", "", texto_brutoyt2022)
  
  # Eliminar HTML
  texto_limpioyt2022 <- gsub("<.*?>", "", texto_limpioyt2022)
  
  # Eliminar signos de puntuación
  texto_limpioyt2022 <- gsub("[[:punct:]]", "", texto_limpioyt2022)
  
  # Agregar el texto limpio a la lista
  textosyt2022 <- c(textosyt2022, texto_limpioyt2022)
}

# Convertir la lista de textos en un solo texto
texto_finalyt2022 <- paste(textosyt2022, collapse = " ")
todos_los_textosyt2022 <- tolower(texto_finalyt2022[[1]])

#Año 2023

# Ruta de la carpeta que contiene los archivos de texto
ruta_carpeta2023 <- "/Users/cienfuegos17/Documents/Universidad/5 Semestre/Ciencia de datos para la toma de decisiones II/Base milenio/2023"

# Lista para almacenar el texto de cada archivo
textosyt2023 <- character(0)

# Recorre cada archivo en la carpeta
archivosyt2023 <- list.files(ruta_carpeta2023, pattern = "\\.txt$", full.names = TRUE)
for (archivoyt2023 in archivosyt2023) {
  # Cargar el texto del archivo con codificación UTF-8
  texto_brutoyt2023 <- readLines(archivoyt2023, warn = FALSE, encoding = "UTF-8")
  
   # Convertir la codificación si es necesario
  texto_brutoyt2023 <- iconv(texto_brutoyt2023, from = "UTF-8", to = "ASCII//TRANSLIT")
  
  # Eliminar URL
  texto_limpioyt2023 <- gsub("http\\S+|www\\S+|ftp\\S+", "", texto_brutoyt2023)
  
  # Eliminar HTML
  texto_limpioyt2023 <- gsub("<.*?>", "", texto_limpioyt2023)
  
  # Eliminar signos de puntuación
  texto_limpioyt2023 <- gsub("[[:punct:]]", "", texto_limpioyt2023)
  
  # Agregar el texto limpio a la lista
  textosyt2023 <- c(textosyt2023, texto_limpioyt2023)
}

# Convertir la lista de textos en un solo texto
texto_finalyt2023 <- paste(textosyt2023, collapse = " ")

# Usa directamente el texto preprocesado
todos_los_textosyt2023 <- tolower(texto_finalyt2023[[1]])

#Wordcloud y frecuencia de palabras

#2018
# Elimina stopwords 
todos_los_textosyt2018 <- removeWords(todos_los_textosyt2018, stopwords("spanish"))
palabras_eliminaryt2018 <- c("milenio","digital","segun","acuer","181","campe","francisco","despis","stema", "huma", "suma","blo","pueb","fblive","forme","santa","reyes","nos","los","tania","con","alejandro", "2018"," recomendamosestoy","usos","ejecucin")

#Juntar todos los textos del 2018 ya sin las stopwords y sin las palabras eliminadas
todos_los_textosyt2018 <- gsub(paste(palabras_eliminaryt2018, collapse = "|"), "", todos_los_textosyt2018, ignore.case = TRUE) 

# Crea la nube de palabras
wordcloudyt2018 <- wordcloud(words = unlist(strsplit(todos_los_textosyt2018, " ")),
          min.freq = 7,
          max.words = 100,  
          random.order = FALSE,
          rot.per = 0.10,  
          scale = c(2, 0.5),
          colors = brewer.pal(10, "Dark2"))
## Warning in brewer.pal(10, "Dark2"): n too large, allowed maximum for palette Dark2 is 8
## Returning the palette you asked for with that many colors
## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents
## Warning in tm_map.SimpleCorpus(corpus, function(x) tm::removeWords(x,
## tm::stopwords())): transformation drops documents

#2019
# Elimina stopwords 
todos_los_textosyt2019 <- removeWords(todos_los_textosyt2019, stopwords("spanish"))
palabras_eliminaryt2019 <- c("idíge", "múca", "legua", "ciol", "maera", "coidad", "cueta", "bie", "aí", "orige", "proce", "glo","viee", "oche", "fieta","publicidad","digital","milenio","sandra","ana","paola","wong","hid","fon","ces","gorno","recomendamosartesanos","viernes","stettin","selene","catalejos","hurgar","especial","alejandro","dar")

#Juntar todos los textos del 2019 ya sin las stopwords y sin las palabras eliminadas
todos_los_textosyt2019 <- gsub(paste(palabras_eliminaryt2019, collapse = "|"), "", todos_los_textosyt2019, ignore.case = TRUE) 

# Crea la nube de palabras
wordcloudyt2019 <- wordcloud(words = unlist(strsplit(todos_los_textosyt2019, " ")),
          min.freq = 7,
          max.words = 100,  
          random.order = FALSE,
          rot.per = 0.05,
          scale = c(1.8, 0.5),
          colors = brewer.pal(10, "Dark2"))
## Warning in brewer.pal(10, "Dark2"): n too large, allowed maximum for palette Dark2 is 8
## Returning the palette you asked for with that many colors
## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents
## Warning in tm_map.SimpleCorpus(corpus, function(x) tm::removeWords(x,
## tm::stopwords())): transformation drops documents

#2020
# Elimina stopwords 
todos_los_textosyt2020 <- removeWords(todos_los_textosyt2020, stopwords("spanish"))
palabras_eliminaryt2020 <- c("digi","publicidad","milenio","villeda","jlmr","para","francisco","azucena","irh","ruiz","rafael","rangel", "reyes","roberto","adolfo","josefina", "tal","karina","alejandro","inm","caen","caejos","mayanegocios","recomendamosautorizan","dan","aparicio","montes","paso","agachar")

#Juntar todos los textos del 2020 ya sin las stopwords y sin las palabras eliminadas
todos_los_textosyt2020 <- gsub(paste(palabras_eliminaryt2020, collapse = "|"), "", todos_los_textosyt2020, ignore.case = TRUE) 

# Crea la nube de palabras
wordcloudyt2020 <- wordcloud(words = unlist(strsplit(todos_los_textosyt2020, " ")),
          min.freq = 4,
          max.words = 100,  
          random.order = FALSE,
          rot.per = 0.05,
          scale = c(1.5, 1),
          colors = brewer.pal(10, "Dark2"))
## Warning in brewer.pal(10, "Dark2"): n too large, allowed maximum for palette Dark2 is 8
## Returning the palette you asked for with that many colors
## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents
## Warning in tm_map.SimpleCorpus(corpus, function(x) tm::removeWords(x,
## tm::stopwords())): transformation drops documents

#2021
# Elimina stopwords 
todos_los_textosyt2021 <- removeWords(todos_los_textosyt2021, stopwords("spanish"))
palabras_eliminaryt2021 <- c("pero", "haber", "tener", "más", "ser", "casi", "uno", "todo", "él", "por", "cada", "con", "ese", "cualquiera", "donde", "desde", "do", "para", "este", "mucho", "que", "como","esto", "las", "era", "muchas", "muy", "los", "una","nos", "sobre", "gente", "nos", "sus", "mis", "mariana", "les", "eso", "sí","fue", "Mariana", "Maribel", "poco", "cuando", "algo", "estaba", "dice", "001", "pues", "entonces", "ahí", "aquí", "imtancia", "imtante", "hoy","ver", "hace", "si","tero","agora","tedz","wong","publicidad","hid","alma","Sandra","Paola","gen","carla","gil","pueb","tratiempos","apolonia","rojas","javier","karla","pcl","amayo","rafael","fon","ledz","trujillo","montes","ces")

#Juntar todos los textos del 2021 ya sin las stopwords y sin las palabras eliminadas
todos_los_textosyt2021 <- gsub(paste(palabras_eliminaryt2021, collapse = "|"), "", todos_los_textosyt2021, ignore.case = TRUE) 

# Crea la nube de palabras
wordcloudyt2021 <- wordcloud(words = unlist(strsplit(todos_los_textosyt2021, " ")),
          min.freq = 5,
          max.words = 100,  
          random.order = FALSE,
          rot.per = 0.10,
          scale = c(2, 0.3),
          colors = brewer.pal(10, "Dark2"))
## Warning in brewer.pal(10, "Dark2"): n too large, allowed maximum for palette Dark2 is 8
## Returning the palette you asked for with that many colors
## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents
## Warning in tm_map.SimpleCorpus(corpus, function(x) tm::removeWords(x,
## tm::stopwords())): transformation drops documents

#2022
# Elimina stopwords 
todos_los_textosyt2022 <- removeWords(todos_los_textosyt2022, stopwords("spanish"))
palabras_eliminaryt2022 <- c("idíge", "múca", "legua", "ciol", "maera", "coidad", "cueta", "bie", "aí", "orige", "proce", "glo","viee", "oche", "fieta","milenio","jeitani","ehr","gerr","eabz","van","luis","golberto","digital","sarkis","mikel","lastra","kvs","gilberto","teodoro","pablo","miranda","amp","wong","jlmr","impera","hoy","paola","recomendamostras","alma","hidalgo","ego","hogarestados","ledz","flc","aldo","publicidad","arellano","bafg","ser","santos")

#Juntar todos los textos del 2022 ya sin las stopwords y sin las palabras eliminadas
todos_los_textosyt2022 <- gsub(paste(palabras_eliminaryt2022, collapse = "|"), "", todos_los_textosyt2022, ignore.case = TRUE) 

# Crea la nube de palabras
wordcloudyt2022 <- wordcloud(words = unlist(strsplit(todos_los_textosyt2022, " ")),
          min.freq = 15,
          max.words = 100,  
          random.order = FALSE,
          rot.per = 0.5,
          scale = c(1.3,.5),
          colors = brewer.pal(10, "Dark2"))
## Warning in brewer.pal(10, "Dark2"): n too large, allowed maximum for palette Dark2 is 8
## Returning the palette you asked for with that many colors
## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents
## Warning in tm_map.SimpleCorpus(corpus, function(x) tm::removeWords(x,
## tm::stopwords())): transformation drops documents

#2023
# Elimina stopwords
todos_los_textosyt2023 <- removeWords(todos_los_textosyt2023, stopwords("spanish"))
palabras_eliminaryt2023 <- c("publicidad","hoyosampliar","2024octavio","enero","sarao","hoy","paola","diego","eduardo","efe","teodoro","expo","tras","dos","javier","vrm","hcm","pnmo","milenio","gaona","isabel","cinco","reyes","agachar","james","estima","dmn","osorno","sur","raeb","recomendamosestoy","embargo","mismo","tanivet","plus","parte","vez","mbg","acuerdo","dan","paso","especialampliar","santa","chm","jaime","trujillo","especial","cabeza","ayu","rap","kevin")

#Juntar todos los textos del 2023 ya sin las stopwords y sin las palabras eliminadas
todos_los_textosyt2023 <- gsub(paste(palabras_eliminaryt2023, collapse = "|"), "", todos_los_textosyt2023, ignore.case = TRUE) 

# Crea la nube de palabras
wordcloudyt2023 <- wordcloud(words = unlist(strsplit(todos_los_textosyt2023, " ")),
          min.freq = 5,
          max.words = 100,  
          random.order = FALSE,
          rot.per = 0.05,
          scale = c(1.4, 0.5),
          colors = brewer.pal(10, "Dark2"))
## Warning in brewer.pal(10, "Dark2"): n too large, allowed maximum for palette Dark2 is 8
## Returning the palette you asked for with that many colors
## Warning in tm_map.SimpleCorpus(corpus, tm::removePunctuation): transformation
## drops documents
## Warning in tm_map.SimpleCorpus(corpus, function(x) tm::removeWords(x,
## tm::stopwords())): transformation drops documents

#análisis de emociones español

#2018
# Calcular las puntuaciones de emociones con la biblioteca 'text'
puntuaciones_emocionesyt2018 <- get_nrc_sentiment(todos_los_textosyt2018, language = "spanish")

# Traducción manual de nombres de emociones (puedes ajustar según tus necesidades)
sentimientos_espanolyt2018 <- c("ira", "anticipacion", "disgusto", "miedo", "alegria", "desconfianza", "positivo", "tristeza", "asombro", "confianza")

# Asignar los nombres traducidos al data frame
colnames(puntuaciones_emocionesyt2018) <- sentimientos_espanolyt2018

# Crear un data frame con los sentimientos y sus valores
sentimientos_dfyt2018 <- data.frame(sentimiento = names(colSums(puntuaciones_emocionesyt2018)), valor = colSums(puntuaciones_emocionesyt2018))

# Ordenar el data frame por frecuencia de sentimientos
sentimientos_dfyt2018 <- sentimientos_dfyt2018 %>% arrange(desc(valor))

ggplot(sentimientos_dfyt2018, aes(x = reorder(sentimiento, -valor), y = valor, fill = sentimiento)) +
  geom_bar(stat = "identity") +
  labs(title = "Puntuaciones de emociones 2018", x = "Sentimiento", y = "Frecuencia") +
  theme_minimal() + scale_fill_brewer(palette = "Set3") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje x

#2019
# Calcular las puntuaciones de emociones con la biblioteca 'text'
puntuaciones_emocionesyt2019 <- get_nrc_sentiment(todos_los_textosyt2019, language = "spanish")

# Traducción manual de nombres de emociones (puedes ajustar según tus necesidades)
sentimientos_espanolyt2019 <- c("ira", "anticipacion", "disgusto", "miedo", "alegria", "desconfianza", "positivo", "tristeza", "asombro", "confianza")

# Asignar los nombres traducidos al data frame
colnames(puntuaciones_emocionesyt2019) <- sentimientos_espanolyt2019

# Crear un data frame con los sentimientos y sus valores
sentimientos_dfyt2019 <- data.frame(sentimiento = names(colSums(puntuaciones_emocionesyt2019)), valor = colSums(puntuaciones_emocionesyt2019))

# Ordenar el data frame por frecuencia de sentimientos
sentimientos_dfyt2019 <- sentimientos_dfyt2019 %>% arrange(desc(valor))

ggplot(sentimientos_dfyt2019, aes(x = reorder(sentimiento, -valor), y = valor, fill = sentimiento)) +
  geom_bar(stat = "identity") +
  labs(title = "Puntuaciones de emociones 2019", x = "Sentimiento", y = "Frecuencia") +
  theme_minimal() + scale_fill_brewer(palette = "Set3") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje x

#2020
# Calcular las puntuaciones de emociones con la biblioteca 'text'
puntuaciones_emocionesyt2020 <- get_nrc_sentiment(todos_los_textosyt2020, language = "spanish")

# Traducción manual de nombres de emociones (puedes ajustar según tus necesidades)
sentimientos_espanolyt2020 <- c("ira", "anticipacion", "disgusto", "miedo", "alegria", "desconfianza", "positivo", "tristeza", "asombro", "confianza")

# Asignar los nombres traducidos al data frame
colnames(puntuaciones_emocionesyt2020) <- sentimientos_espanolyt2020

# Crear un data frame con los sentimientos y sus valores
sentimientos_dfyt2020 <- data.frame(sentimiento = names(colSums(puntuaciones_emocionesyt2020)), valor = colSums(puntuaciones_emocionesyt2020))

# Ordenar el data frame por frecuencia de sentimientos
sentimientos_dfyt2020 <- sentimientos_dfyt2020 %>% arrange(desc(valor))

ggplot(sentimientos_dfyt2020, aes(x = reorder(sentimiento, -valor), y = valor, fill = sentimiento)) +
  geom_bar(stat = "identity") +
  labs(title = "Puntuaciones de emociones 2020", x = "Sentimiento", y = "Frecuencia") +
  theme_minimal() + scale_fill_brewer(palette = "Set3") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje x

#2021
# Calcular las puntuaciones de emociones con la biblioteca 'text'
puntuaciones_emocionesyt2021 <- get_nrc_sentiment(todos_los_textosyt2021, language = "spanish")

# Traducción manual de nombres de emociones (puedes ajustar según tus necesidades)
sentimientos_espanolyt2021 <- c("ira", "anticipacion", "disgusto", "miedo", "alegria", "desconfianza", "positivo", "tristeza", "asombro", "confianza")

# Asignar los nombres traducidos al data frame
colnames(puntuaciones_emocionesyt2021) <- sentimientos_espanolyt2021

# Crear un data frame con los sentimientos y sus valores
sentimientos_dfyt2021 <- data.frame(sentimiento = names(colSums(puntuaciones_emocionesyt2021)), valor = colSums(puntuaciones_emocionesyt2021))

# Ordenar el data frame por frecuencia de sentimientos
sentimientos_dfyt2021 <- sentimientos_dfyt2021 %>% arrange(desc(valor))

ggplot(sentimientos_dfyt2021, aes(x = reorder(sentimiento, -valor), y = valor, fill = sentimiento)) +
  geom_bar(stat = "identity") +
  labs(title = "Puntuaciones de emociones 2021", x = "Sentimiento", y = "Frecuencia") +
  theme_minimal() + scale_fill_brewer(palette = "Set3") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje x

#2022
# Calcular las puntuaciones de emociones con la biblioteca 'text'
puntuaciones_emocionesyt2022 <- get_nrc_sentiment(todos_los_textosyt2022, language = "spanish")

# Traducción manual de nombres de emociones (puedes ajustar según tus necesidades)
sentimientos_espanolyt2022 <- c("ira", "anticipacion", "disgusto", "miedo", "alegria", "desconfianza", "positivo", "tristeza", "asombro", "confianza")

# Asignar los nombres traducidos al data frame
colnames(puntuaciones_emocionesyt2022) <- sentimientos_espanolyt2022

# Crear un data frame con los sentimientos y sus valores
sentimientos_dfyt2022 <- data.frame(sentimiento = names(colSums(puntuaciones_emocionesyt2022)), valor = colSums(puntuaciones_emocionesyt2022))

# Ordenar el data frame por frecuencia de sentimientos
sentimientos_dfyt2022 <- sentimientos_dfyt2022 %>% arrange(desc(valor))

ggplot(sentimientos_dfyt2022, aes(x = reorder(sentimiento, -valor), y = valor, fill = sentimiento)) +
  geom_bar(stat = "identity") +
  labs(title = "Puntuaciones de emociones 2022", x = "Sentimiento", y = "Frecuencia") +
  theme_minimal() + scale_fill_brewer(palette = "Set3") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje x

#2023
# Calcular las puntuaciones de emociones con la biblioteca 'text'
puntuaciones_emocionesyt2023 <- get_nrc_sentiment(todos_los_textosyt2023, language = "spanish")

# Traducción manual de nombres de emociones (puedes ajustar según tus necesidades)
sentimientos_espanolyt2023 <- c("ira", "anticipacion", "disgusto", "miedo", "alegria", "desconfianza", "positivo", "tristeza", "asombro", "confianza")

# Asignar los nombres traducidos al data frame
colnames(puntuaciones_emocionesyt2023) <- sentimientos_espanolyt2023

# Crear un data frame con los sentimientos y sus valores
sentimientos_dfyt2023 <- data.frame(sentimiento = names(colSums(puntuaciones_emocionesyt2023)), valor = colSums(puntuaciones_emocionesyt2023))

# Ordenar el data frame por frecuencia de sentimientos
sentimientos_dfyt2023 <- sentimientos_dfyt2023 %>% arrange(desc(valor))

ggplot(sentimientos_dfyt2023, aes(x = reorder(sentimiento, -valor), y = valor, fill = sentimiento)) +
  geom_bar(stat = "identity") +
  labs(title = "Puntuaciones de emociones 2023", x = "Sentimiento", y = "Frecuencia") +
  theme_minimal() + scale_fill_brewer(palette = "Set3") +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))  # Rotar etiquetas del eje x

#Análisis de tópicos

#2018
# Definir el número de tópicos
corpusyt2018 <- Corpus(VectorSource(todos_los_textosyt2018))
dtmyt2018 <- DocumentTermMatrix(corpusyt2018)
num_topics <- 5

# Generar el modelo LDA
lda_modelyt2018 <- LDA(dtmyt2018, k = num_topics)

# Obtener los términos más importantes de cada tópico
termsyt2018 <- tidy(lda_modelyt2018, matrix = "beta") %>%
  group_by(topic) %>%
  top_n(5, wt = beta)

# Graficar la distribución de documentos en tópicos
ggplot(termsyt2018, aes(x = term, y = beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  labs(title = "Distribución de Términos en Tópicos 2018",
       x = "Término",
       y = "Peso Beta") +
  theme_minimal()

#2019
# Definir el número de tópicos
corpusyt2019 <- Corpus(VectorSource(todos_los_textosyt2019))
dtmyt2019 <- DocumentTermMatrix(corpusyt2019)
num_topics <- 5

# Generar el modelo LDA
lda_modelyt2019 <- LDA(dtmyt2019, k = num_topics)

# Obtener los términos más importantes de cada tópico
termsyt2019 <- tidy(lda_modelyt2019, matrix = "beta") %>%
  group_by(topic) %>%
  top_n(5, wt = beta)

# Graficar la distribución de documentos en tópicos
ggplot(termsyt2019, aes(x = term, y = beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  labs(title = "Distribución de Términos en Tópicos 2019",
       x = "Término",
       y = "Peso Beta") +
  theme_minimal()

#2020
# Definir el número de tópicos
corpusyt2020 <- Corpus(VectorSource(todos_los_textosyt2020))
dtmyt2020 <- DocumentTermMatrix(corpusyt2020)
num_topics <- 5

# Generar el modelo LDA
lda_modelyt2020 <- LDA(dtmyt2020, k = num_topics)

# Obtener los términos más importantes de cada tópico
termsyt2020 <- tidy(lda_modelyt2020, matrix = "beta") %>%
  group_by(topic) %>%
  top_n(5, wt = beta)

# Graficar la distribución de documentos en tópicos
ggplot(termsyt2020, aes(x = term, y = beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  labs(title = "Distribución de Términos en Tópicos 2020",
       x = "Término",
       y = "Peso Beta") +
  theme_minimal()

#2021
# Definir el número de tópicos
corpusyt2021 <- Corpus(VectorSource(todos_los_textosyt2021))
dtmyt2021 <- DocumentTermMatrix(corpusyt2021)
num_topics <- 5

# Generar el modelo LDA
lda_modelyt2021 <- LDA(dtmyt2021, k = num_topics)

# Obtener los términos más importantes de cada tópico
termsyt2021 <- tidy(lda_modelyt2021, matrix = "beta") %>%
  group_by(topic) %>%
  top_n(5, wt = beta)

# Graficar la distribución de documentos en tópicos
ggplot(termsyt2021, aes(x = term, y = beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  labs(title = "Distribución de Términos en Tópicos 2021",
       x = "Término",
       y = "Peso Beta") +
  theme_minimal()

#2022
# Definir el número de tópicos
corpusyt2022 <- Corpus(VectorSource(todos_los_textosyt2022))
dtmyt2022 <- DocumentTermMatrix(corpusyt2022)
num_topics <- 5

# Generar el modelo LDA
lda_modelyt2022 <- LDA(dtmyt2022, k = num_topics)

# Obtener los términos más importantes de cada tópico
termsyt2022 <- tidy(lda_modelyt2022, matrix = "beta") %>%
  group_by(topic) %>%
  top_n(5, wt = beta)

# Graficar la distribución de documentos en tópicos
ggplot(termsyt2022, aes(x = term, y = beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  labs(title = "Distribución de Términos en Tópicos 2022",
       x = "Término",
       y = "Peso Beta") +
  theme_minimal()

#2023
# Definir el número de tópicos
corpusyt2023 <- Corpus(VectorSource(todos_los_textosyt2023))
dtmyt2023 <- DocumentTermMatrix(corpusyt2023)
num_topics <- 5

# Generar el modelo LDA
lda_modelyt2023 <- LDA(dtmyt2023, k = num_topics)

# Obtener los términos más importantes de cada tópico
termsyt2023 <- tidy(lda_modelyt2023, matrix = "beta") %>%
  group_by(topic) %>%
  top_n(5, wt = beta)

# Graficar la distribución de documentos en tópicos
ggplot(termsyt2023, aes(x = term, y = beta, fill = factor(topic))) +
  geom_col(show.legend = FALSE) +
  coord_flip() +
  facet_wrap(~topic, scales = "free_y", ncol = 3) +
  labs(title = "Distribución de Términos en Tópicos 2023",
       x = "Término",
       y = "Peso Beta") +
  theme_minimal()