Seleccione un libro, diferente al utilizado en el primer taller de este corte, de alguna de las siguientes dos fuentes:

Paquetes necesarios

library(tm)
library(SnowballC)
library(wordcloud)
library(ggplot2)
library(dplyr)
library(readr)
library(cluster)
library(tm)
library(SnowballC)
library(gutenbergr)
library(syuzhet)
library(stringr)

Leyendo los datos

  • Primero estableclemos el directorio de trabajo
getwd()
## [1] "C:/Users/wsand/Dropbox/2021-II"
setwd("C:/Users/wsand/Dropbox/2021-II")

2. Importando los datos

# install.packages("gutenberg")
library(gutenbergr)
descarga <- gutenberg_download(9890, strip = TRUE)


obra1 <- descarga$text

Encoding(obra1) <- 'latin1'

library("syuzhet")
#write.table(obra1, file="obra1.txt")

oraciones <- get_sentences(obra1)

1. Realice las depuraciones necesarias para eliminar palabras y símbolos que no aportan en el análisis del texto

Limpieza de texto

  • Eliminamos primeras filas de notas, prólogo, post-prólogo
# write.table(oraciones, file="oraciones.txt")
total_lineas <- length(oraciones)
linea_empieza <- 43
linea_final <- total_lineas - linea_empieza

texto_limpio <- oraciones[linea_empieza:linea_final]
#write.table(texto_limpio, file="texto_limpio.txt")


texto_limpio <- removeWords(texto_limpio, words = stopwords("spanish"))

texto_limpio <- stripWhitespace(texto_limpio)
#write.table(texto_limpio, file="texto_limpio.txt")

texto_limpio <- texto_limpio %>% 
  str_replace_all(., "[[:cntrl:]]", " ") %>% 
  str_to_lower() %>% 
  removePunctuation() %>% 
  str_replace_all(., "-", " ")

nov_raw<-texto_limpio

# Preparación del texto
str(nov_raw)
##  chr [1:2965] "" "el general bolívar delgado menos regular estatura" ...
  • Creación de “párrafos”
diez <- rep(1:ceiling(length(nov_raw)/10), each = 10)
diez <- diez[1:length(nov_raw)]
nov_text <- cbind(diez, nov_raw) %>% data.frame()
nov_text <- aggregate(formula = nov_raw ~ diez,data = nov_text,FUN = paste,collapse = " ")
nov_text <- nov_text %>%dplyr::select(nov_raw) %>% as.matrix
dim(nov_text)
## [1] 297   1
#(nov_text, file="nov_text.txt")

Limpieza de texto

nov_text <- gsub("[[:cntrl:]]", " ", nov_text)
nov_text <- gsub("[^[:alnum:][:blank:]+?&/\\-]", "", nov_text)
nov_text <- tolower(nov_text)
nov_text <- removeWords(nov_text, words = stopwords("spanish"))
nov_text <- removePunctuation(nov_text)
nov_text <- removeNumbers(nov_text)
nov_text <- stripWhitespace(nov_text)

Análisis del Corpus

nov_corpus <- Corpus(VectorSource(nov_text))
nov_corpus
## <<SimpleCorpus>>
## Metadata:  corpus specific: 1, document level (indexed): 0
## Content:  documents: 297

Nube de palabras

nov_tdm <- TermDocumentMatrix(nov_corpus)
nov_tdm
## <<TermDocumentMatrix (terms: 4778, documents: 297)>>
## Non-/sparse entries: 12794/1406272
## Sparsity           : 99%
## Maximal term length: 33
## Weighting          : term frequency (tf)

Frecuencia de palabras

nov_mat <- as.matrix(nov_tdm)
dim(nov_mat)
## [1] 4778  297
nov_mat <- nov_mat %>% rowSums() %>% sort(decreasing = TRUE)
nov_mat <- data.frame(palabra = names(nov_mat), frec = nov_mat)
wordcloud(
  words = nov_mat$palabra, 
  freq = nov_mat$frec,
  max.words = 80, 
  random.order = F, 
  colors=brewer.pal(name = "Dark2", n = 8)
)

nov_mat[1:20, ]
##               palabra frec
## bolívar       bolívar  126
## mas               mas  114
## general       general   97
## habia           habia   83
## despues       despues   77
## gobierno     gobierno   62
## jefe             jefe   58
## congreso     congreso   57
## fué               fué   56
## dia               dia   55
## libertador libertador   53
## venezuela   venezuela   52
## hombres       hombres   50
## carácas       carácas   44
## mismo           mismo   43
## pueblo         pueblo   42
## don               don   40
## poder           poder   40
## dias             dias   40
## año               año   39

Más depuración

nov_text <- removeWords(nov_text, words = c( "mas",   "despues",
                                            "habia","fué"))

nov_corpus <- nov_text %>% VectorSource() %>% Corpus()
nov_tdm <- TermDocumentMatrix(nov_corpus)
nov_tdm
## <<TermDocumentMatrix (terms: 4774, documents: 297)>>
## Non-/sparse entries: 12507/1405371
## Sparsity           : 99%
## Maximal term length: 33
## Weighting          : term frequency (tf)

2. Realice un análisis de asociaciones entre las cuatro (4) palabras más frecuentes en el texto. Establezca el coeficiente de correlación más adecuado.

nov_mat <- as.matrix(nov_tdm)
dim(nov_mat)
## [1] 4774  297
nov_mat <- nov_mat %>% rowSums() %>% sort(decreasing = TRUE)
nov_mat <- data.frame(palabra = names(nov_mat), frec = nov_mat)
wordcloud(
  words = nov_mat$palabra, 
  freq = nov_mat$frec, 
  max.words = 80, 
  random.order = F, 
  colors=brewer.pal(name = "Dark2", n = 8)
)

nov_mat[1:20, ]
##               palabra frec
## bolívar       bolívar  126
## general       general   97
## gobierno     gobierno   62
## jefe             jefe   58
## congreso     congreso   57
## dia               dia   55
## libertador libertador   53
## venezuela   venezuela   52
## hombres       hombres   50
## carácas       carácas   44
## mismo           mismo   43
## pueblo         pueblo   42
## don               don   40
## poder           poder   40
## dias             dias   40
## año               año   39
## dos               dos   38
## armas           armas   38
## asi               asi   37
## coronel       coronel   37
# Gráficas de frecuencia
nov_mat[1:10, ] %>%
  ggplot(aes(palabra, frec)) +
  geom_bar(stat = "identity", color = "black", fill = "#87CEFA") +
  geom_text(aes(hjust = 1.3, label = frec)) + 
  coord_flip() + 
  labs(title = "Diez palabras más frecuentes en Bolívar",  x = "Palabras", 
       y = "Número de usos")

nov_mat %>%
  mutate(perc = (frec/sum(frec))*100) %>%
  .[1:10, ] %>%
  ggplot(aes(palabra, perc)) +
  geom_bar(stat = "identity", color = "black", fill = "#87CEFA") +
  geom_text(aes(hjust = 1.3, label = round(perc, 2))) + 
  coord_flip() +
  labs(title = "Diez palabras más frecuentes en Bolívar", x = "Palabras", 
       y = "Porcentaje de uso")

# Asociaciones entre palabras
findAssocs(nov_tdm, terms = c("bolívar", "general", "jefe", "gobierno"), 
           corlimit = .25)
## $bolívar
## division 
##     0.27 
## 
## $general
##   capitan     segun funciones  ayacucho 
##      0.29      0.27      0.26      0.25 
## 
## $jefe
##    ascendia encontraban 
##        0.26        0.26 
## 
## $gobierno
## voluntad absoluta 
##      0.3      0.3

3.Realice un agrupamiento jerárquico y obtenga los dendogramas respectivos, empleando:

Agrupamiento jerárquico (Hierarchical clustering)

  • Eliminar términos dispersos
nov_new <- removeSparseTerms(nov_tdm, sparse = .95)
nov_tdm
## <<TermDocumentMatrix (terms: 4774, documents: 297)>>
## Non-/sparse entries: 12507/1405371
## Sparsity           : 99%
## Maximal term length: 33
## Weighting          : term frequency (tf)
nov_new
## <<TermDocumentMatrix (terms: 133, documents: 297)>>
## Non-/sparse entries: 3261/36240
## Sparsity           : 92%
## Maximal term length: 13
## Weighting          : term frequency (tf)
nov_tdm$nrow
## [1] 4774
nov_new$nrow
## [1] 133
nov_new <- nov_new %>% as.matrix()

Matriz de distancia

nov_new <- nov_new / rowSums(nov_new)
nov_dist <- dist(nov_new, method = "euclidian")
dev.new(width=10, height=10, unit="in")

plot(as.dendrogram(hclust(nov_dist)), horiz = T)

hclust

nov_hclust <-  hclust(nov_dist, method = "ward.D")
plot(nov_hclust, main = "Dendrograma de Bolívar - hclust", sub = "", xlab = "", cex = 0.6)

plot(nov_hclust, main = "Dendrograma de Bolívar - hclust", sub = "", xlab = "", cex = 0.6)
rect.hclust(nov_hclust, k = 10, border="blue")

Agnes (Agglomerative Nesting)

nov_agnes <- agnes(nov_dist, method = "average")
plot(nov_agnes, which.plots = 2, main = "Dendrograma de Bolívar - Agnes", 
     sub = "", xlab = "", cex = 0.6)

plot(nov_agnes, which.plots = 2, main = "Dendrograma de Bolívar - Agnes", 
     sub = "", xlab = "", cex = 0.6)
rect.hclust(nov_agnes, k = 10, border = "blue")

4. Obtenga diez (10) conclusiones sobre el contenido del libro. Por ejemplo: principales personajes, argumento, época en la que se desarrolla, etc.