Proyecto final ciencia de datos.

(analisis de la empresa NIKE)

-leomaris ferreras

-matricula:2021-1123

1. Introducción

en este tabajo estare analizando la empresa NIKE la cual es una empresa de calsado conocida mundialmente, en el analisis siguiente estare tocando los siguientes temas:

#credencial

```{r eval=FALSE} consumerKey <- “x4W2OSWlqaEHTAWgMvJYw5gvm” consumerSecret <- “cLi5AJZfprRP0ZJSf32euZY6nOr6uz9FPzVzAqBjMov72lFODq”

accessToken <- “1371865708204851203-y6UaH2FzKe3rN1cS1v8Kq8UE8SaW0I” accessSecret <- “Dd55zQ48T4rWCKPwoiF7grqnWTG0zntM5oSgUcnZumeGL” options(httr_oauth_cache=TRUE) setup_twitter_oauth(consumer_key = consumerKey, consumer_secret = consumerSecret,access_token = accessToken, access_secret = accessSecret)


# 3. Extracción de tweets a través de R

Antes de comenzar, no debemos olvidar cargar nuestras credenciales (twitter_token):

```{r}
#direccion del token
getwd()
home_directory <- path.expand("C:/Users/leomaris/Dropbox/Mi PC (DESKTOP-ONRHE0G)/Documents/lenguajenatural/matemarica aplicada en R/matemarica aplicada en R/proyecto final dos")
file_name <- file.path(home_directory,"twitter_token.rds")
saveRDS("twitter_token.RDS", file = "lenguajenatural")

home_directory = path.expand("C:/Users/leomaris/Dropbox/Mi PC (DESKTOP-ONRHE0G)/Documents/lenguajenatural/matemarica aplicada en R/matemarica aplicada en R/proyecto final dos")
file_name = file.path(home_directory,"twitter_token.rds")
twitter_token.RDS = readRDS(file = "lenguajenatural")

librerías:

# Carga de librerías
library(rtweet)
library(tidyverse)
library(tidytext)
library(waffle)
library(tm)
library(stopwords)
library(wordcloud2)
library(syuzhet)
library(stringi)
library(parallel)
library(udpipe)

tendencias en Twitter, simplemente debemos utilizar la función trends_available.

# Función de codificación geográfica 
trends_available() %>% filter(countryCode=="DO")
# Tendencias para el "woeid" de REPUBLICA DOMINICANA
get_trends(woeid =  23424800)
# Tendencias para el "woeid" de REPUBLICA DOMINICANA
get_trends(woeid =  23424800)

extraer datos de un hashtag

# Extraer data de un hashtag 
tweets_ec = search_tweets(q = "#BlackLivesMatter", n = 10000, lang="es")

tweets_ec %>% head()

estraer datos de la empresa NIKE

# Extraer data de un usuario
user_tweets_ec = get_timeline(user = "@Nike", n = 3200, lang="es")

user_tweets_ec %>% head()

4. Limpieza de datos

# Tweets orgánicos
user_tweets_ec_organic = user_tweets_ec %>% filter(is_retweet==F, is.na(reply_to_status_id))

# Retweets
user_tweets_ec_retweets = user_tweets_ec %>% filter(is_retweet==T)

# Respuestas
user_tweets_ec_replies = user_tweets_ec %>% filter(!is.na(reply_to_status_id))

limpieza de textos

# Limpieza de textos
user_tweets_ec_organic = user_tweets_ec_organic %>% 
  mutate(text=str_replace_all(text, "https\\S*", "")) %>% # hipervínculos
  mutate(text=str_replace_all(text, "@\\S*", "")) %>% # menciones
  mutate(text=str_replace_all(text, "[\r\n\t]", "")) %>% # separadores
  mutate(text=removeNumbers(text)) %>% # números
  mutate(text=removePunctuation(text)) %>%  # puntuacion
  mutate(text=str_squish(text))

Acto seguido quitamos **palabras vacías*.

# Palabras vacías
stopwords_snow = stopwords("es", source = "snowball")
stopwords_iso = stopwords("es", source = "stopwords-iso")
stopwords_ntlk = stopwords("es", source = "nltk")
# Conteo de palabras
tweets = user_tweets_ec_organic %>%
  select(text) %>%
  unnest_tokens(token, text, to_lower = F)
tweets = tweets %>%
  filter(!token %in% c(stopwords_ntlk))

Una tarea adicional que se lleva a cabo en este tipo de análisis es el stemming o la lematización. Estos son métodos para reducir una palabra a su raíz o morfema con el objetivo de analizar variaciones de una palabra como una sola.

# Descarga de modelo preentrenado udpipe
#udpipe::udpipe_download_model('spanish') # Descomentar al ejecutar por primera vez 
udpipe_download_model('spanish')
model = udpipe_load_model("spanish-gsd-ud-2.5-191206.udpipe")
tweets_ann = as_tibble(udpipe_annotate(model, tweets$token))

conteo de palabras

# Conteo de palabras
tweets = tweets_ann %>%
  select(token, lemma) %>%
  filter(!is.na(lemma))

tweets = tweets %>%
  mutate(lemma=tolower(lemma)) %>%
  filter(!lemma %in% c(stopwords_ntlk))

resultado de esta limpieza y procesamiento de los datos:

tweets %>% head(7)

5. Análisis descriptivo

Una vez que tenemos los datos extraídos limpios, realizaremos algunos análisis descriptivos para extraer conclusiones acerca del manejo de la cuenta de Twitter de NIKE:

Top tweets por conteo de likes

# Top de tweets por conteo de likes
user_tweets_ec = user_tweets_ec %>% arrange(desc(favorite_count))
user_tweets_ec %>% head(5) %>% select(text)

Top tweets por conteo de retweets

# Top de tweets por conteo de retweets
user_tweets_ec = user_tweets_ec %>% arrange(-retweet_count)
user_tweets_ec %>% head(5) %>% select(text)

Composición de los tweets

# Composición de los tweets
CountTweets = data.frame(tipo=c("orgánico","retweets","respuestas"),
                         conteo=c(nrow(user_tweets_ec_organic), 
                                  nrow(user_tweets_ec_retweets), 
                                  nrow(user_tweets_ec_replies)))
CountTweets = CountTweets %>% 
  mutate(porcentaje=round(conteo/sum(conteo)*100,0)) %>% 
  arrange(desc(conteo))
CountTweets
# Gráfico de la composición de tweets
w_vec = CountTweets$porcentaje
names(w_vec) = CountTweets$tipo
waffle(w_vec, rows = 10, title = 'NIKE: Tweets por origen')

Evolución temporal de los tweets por día

# Gráfico de la evolución de tweets
ts_plot(user_tweets_ec, by="day", color="darkred") +
  labs(x = "Fecha", y = NULL, title = "Frecuencia de los tweets de la NIKE", 
       subtitle = "Conteo de tweets agregado por día", caption = "Fuente: Twitter") +
  theme_bw()

Fuente de publicación de los tweets

# Fuente de los tweets
user_tweets_ec_sources = user_tweets_ec %>% 
  group_by(source) %>%
  summarize(conteo=n()) %>% 
  mutate(porcentaje=round(conteo/sum(conteo)*100,0)) %>% 
  arrange(desc(conteo))
user_tweets_ec_sources
# Gráfico de la fuente de los tweets
w_vec2 = user_tweets_ec_sources$porcentaje
names(w_vec2) = user_tweets_ec_sources$source
waffle(w_vec2, rows = 10, title = 'NIKE: Tweets por fuente')
# Hashtags más comunes
data.frame(text=unlist(user_tweets_ec_organic$hashtags)) %>% 
  count(text, sort = TRUE) %>%
  top_n(15) %>%
  mutate(text = reorder(text, n)) %>%
  ggplot(aes(x = text, y = n)) +
  geom_col() +
  xlab(NULL) +
  coord_flip() +
  labs(y = "Frecuencia",
       x = "Hashtags",
       title = "Hashtags más frecuentes en la cuenta de Twitter de nike",
       subtitle = "Tweets orgánicos de NIKE")
# Hashtags más comunes
data.frame(text=unlist(user_tweets_ec_organic$hashtags)) %>%
  count(text, sort = TRUE) %>%
  mutate(text = reorder(text, n)) %>%
  select(word=text, freq=n) %>%
  wordcloud2()

Palabras más usadas en los tweets

# Palabras más usadas
tweets %>%
  count(lemma, sort = TRUE) %>%
  top_n(10) %>%
  mutate(lemma = reorder(lemma, n)) %>%
  ggplot(aes(x = lemma, y = n)) +
  geom_col() +
  xlab(NULL) +
  coord_flip() +
  labs(y = "Frecuencia",
       x = "Palabras",
       title = "Palabras más frecuentes en la cuenta de Twitter de nike")


# Palabras más usadas
tweets %>% 
  count(lemma, sort = TRUE) %>%
  mutate(lemma = reorder(lemma, n)) %>%
  select(word=lemma, freq=n) %>% 
  wordcloud2()

6. Análisis de sentimientos

Cuando tenemos datos de texto podemos realizar además análisis de sentimientos.


# Creación del ambiente de paralelización
cl = makeCluster(detectCores()-1)
clusterExport(cl = cl, c("get_sentiment", "get_sent_values", "get_nrc_sentiment", "get_nrc_values", "parLapply"))

# Análisis de sentimientos
tweet_sentiment_nrc = get_nrc_sentiment(tweets$lemma,language = "spanish", cl=cl)

# Etiquetado de sentimientos
tweet_sentiment_nrc = cbind(tweets, tweet_sentiment_nrc)
tweet_sentiment_nrc %>% filter(rowSums(tweet_sentiment_nrc[,-c(1,2)]) > 0) %>% head()
  token     lemma anger anticipation disgust fear joy sadness surprise trust negative positive

Gráficamente, los sentimientos más recurrentes en los tweets de NIKE son:

# Frecuencia de sentimientos
sentimentscores = data.frame(colSums(tweet_sentiment_nrc %>% filter(lemma!="general") %>% 
                                       select(-token,-lemma)))
names(sentimentscores) = "Score"
sentimentscores = cbind("sentiment"=rownames(sentimentscores),sentimentscores)
rownames(sentimentscores) = NULL
sentimentscores = sentimentscores %>% 
  mutate(sentiment = recode(sentiment, 
                            "anger"="enfado",
                            "anticipation"="anticipación",
                            "disgust"="disgusto",
                            "fear"="miedo",
                            "joy"="alegría",
                            "negative"="negativo",
                            "positive"="positivo",
                            "sadness"="tristeza",
                            "surprise"="sorpresa",
                            "trust"="confianza"))

ggplot(data=sentimentscores,aes(x=sentiment,y=Score))+
  geom_bar(aes(fill=sentiment),stat = "identity")+
  xlab("Sentimientos")+ylab("Scores")+
  ggtitle("Sentimientos totales basados en scores")+
  theme(axis.text.x = element_text(angle=90),
        legend.position = "none")
tweet_sentiment_nrc %>% 
  filter(fear > 0) %>% 
  select(lemma) %>% 
  count(lemma) %>% 
  select(word=lemma, freq=n) %>% 
  wordcloud2()


hasta aqui ha llegado mi analisis de la empresa NIKE.