R Markdown

This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.

Opção 1 - TWITTER

Parte 1 - Capturar dados via API do Twitter

##Seguindo a orientação do tutorial 9 de Leonardo Barone (https://github.com/leobarone/mq_ufmg_17/blob/master/mq_ufmg_2017_tutorial9.Rmd)

###Acessamos a conta no Twitter. 
###Entramos no endereço https://apps.twitter.com/ e criamos o API em "Create New App", o campo "Callback URL" foi preenchido com "http://127.0.0.1:1410".

###Na página inicial do Twitter Apps criado. Clicamos na aba "Keys and Access Tokens".
####As chaves abaixo foram consideradas necessárias para estabelecer a conexão com o Twitter no R.
#####"Consumer Key (API Key)" = aoTABBVtpV0QFCmvOe8PlFPN9
#####"Consumer Secret (API Secret)" = u2cOMC7sFB5FhyQpounyHKTmADpjVQ8l6Vh37VZo7AiVM0U93c
#####"Access Token" =   3867337641-TrkfjyWA5qq5glaKHDxJySUihswEGVIDXFLWy0p
#####"Access Token Secret" = 3T2AklkMuGdcQgSUyDaz7DAWCcXZqKGdmPz65CwSWiB7Z

###Pacotes necessários: twitteR, ROAuth (para autenticar conexões na web) e httr (para fazer requisições http, "http requests")
library(ROAuth)
library(httr)
library(twitteR)

###Função setup_twitter_oauth: recebe como parâmetros as "chaves" (armazenadas em objetos) para conexão com o Twitter via R

consumer_key <- "aoTABBVtpV0QFCmvOe8PlFPN9"
consumer_secret <- "u2cOMC7sFB5FhyQpounyHKTmADpjVQ8l6Vh37VZo7AiVM0U93c"
access_token <- "3867337641-TrkfjyWA5qq5glaKHDxJySUihswEGVIDXFLWy0p"
access_secret <- "3T2AklkMuGdcQgSUyDaz7DAWCcXZqKGdmPz65CwSWiB7Z"

setup_twitter_oauth(consumer_key,
                    consumer_secret,
                    access_token,
                    access_secret)
## [1] "Using direct authentication"
##Função "searchTwitter": procura tweets utilizando hashtags ou termos chave. Resulta em uma lista de informações sobre os tweets com o tema. Podemos "filtrar" a busca pela quantidade de tweets desejada, por idioma (lang), data inicial (since), data final (until), localidade ou proximidade radial a uma lat/long(geocode), etc.
##Função "str": examina a estrutura dos tweets.

###TERMO ESCOLHIDO: DISLEXIA
tweets <- searchTwitter("dislexia", n = 500, lang = 'pt')
head(tweets)
## [[1]]
## [1] "btshape: RT @pjmstrunk: la dislexia se pega? pregunto ahqq"
## 
## [[2]]
## [1] "pjmstrunk: la dislexia se pega? pregunto ahqq"
## 
## [[3]]
## [1] "Dejota_RP: Beije minha boca e diz que tem dislexia #broxante"
## 
## [[4]]
## [1] "yagogustav0: tenho uma leve dislexia"
## 
## [[5]]
## [1] "luana0bass: eu devo ter dislexia certeza"
## 
## [[6]]
## [1] "TattooRafaaa: A câmera do iPhone tipo eh dislexia pq eh do lado errado a sai a foto"
str(tweets[[1]])
## Reference class 'status' [package "twitteR"] with 17 fields
##  $ text         : chr "RT @pjmstrunk: la dislexia se pega? pregunto ahqq"
##  $ favorited    : logi FALSE
##  $ favoriteCount: num 0
##  $ replyToSN    : chr(0) 
##  $ created      : POSIXct[1:1], format: "2017-09-04 02:49:54"
##  $ truncated    : logi FALSE
##  $ replyToSID   : chr(0) 
##  $ id           : chr "904536973196632065"
##  $ replyToUID   : chr(0) 
##  $ statusSource : chr "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>"
##  $ screenName   : chr "btshape"
##  $ retweetCount : num 1
##  $ isRetweet    : logi TRUE
##  $ retweeted    : logi FALSE
##  $ longitude    : chr(0) 
##  $ latitude     : chr(0) 
##  $ urls         :'data.frame':   0 obs. of  4 variables:
##   ..$ url         : chr(0) 
##   ..$ expanded_url: chr(0) 
##   ..$ dispaly_url : chr(0) 
##   ..$ indices     : num(0) 
##  and 53 methods, of which 39 are  possibly relevant:
##    getCreated, getFavoriteCount, getFavorited, getId, getIsRetweet,
##    getLatitude, getLongitude, getReplyToSID, getReplyToSN, getReplyToUID,
##    getRetweetCount, getRetweeted, getRetweeters, getRetweets,
##    getScreenName, getStatusSource, getText, getTruncated, getUrls,
##    initialize, setCreated, setFavoriteCount, setFavorited, setId,
##    setIsRetweet, setLatitude, setLongitude, setReplyToSID, setReplyToSN,
##    setReplyToUID, setRetweetCount, setRetweeted, setScreenName,
##    setStatusSource, setText, setTruncated, setUrls, toDataFrame,
##    toDataFrame#twitterObj
##Reorganizando as 16 informaçoes em uma matriz de dados com a função "twListToDF"

df.tweets <- twListToDF(tweets)
str(df.tweets)
## 'data.frame':    500 obs. of  16 variables:
##  $ text         : chr  "RT @pjmstrunk: la dislexia se pega? pregunto ahqq" "la dislexia se pega? pregunto ahqq" "Beije minha boca e diz que tem dislexia #broxante" "tenho uma leve dislexia" ...
##  $ favorited    : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
##  $ favoriteCount: num  0 0 0 0 1 1 0 0 0 0 ...
##  $ replyToSN    : chr  NA NA NA NA ...
##  $ created      : POSIXct, format: "2017-09-04 02:49:54" "2017-09-04 01:43:55" ...
##  $ truncated    : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
##  $ replyToSID   : chr  NA NA NA NA ...
##  $ id           : chr  "904536973196632065" "904520367255031808" "904518761465741313" "904516950629502977" ...
##  $ replyToUID   : chr  NA NA NA NA ...
##  $ statusSource : chr  "<a href=\"http://twitter.com/download/iphone\" rel=\"nofollow\">Twitter for iPhone</a>" "<a href=\"http://twitter.com/download/android\" rel=\"nofollow\">Twitter for Android</a>" "<a href=\"http://twitter.com/download/android\" rel=\"nofollow\">Twitter for Android</a>" "<a href=\"http://twitter.com/download/android\" rel=\"nofollow\">Twitter for Android</a>" ...
##  $ screenName   : chr  "btshape" "pjmstrunk" "Dejota_RP" "yagogustav0" ...
##  $ retweetCount : num  1 1 0 0 0 0 0 0 0 4 ...
##  $ isRetweet    : logi  TRUE FALSE FALSE FALSE FALSE FALSE ...
##  $ retweeted    : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
##  $ longitude    : logi  NA NA NA NA NA NA ...
##  $ latitude     : logi  NA NA NA NA NA NA ...
##função "strip_retweets": remove os retweets da lista de tweets

tweets_noret <- strip_retweets(tweets, strip_manual=TRUE, strip_mt=TRUE)
df.tweets_noret <- twListToDF(tweets_noret)
df.tweets_noret$text[1:10]
##  [1] "la dislexia se pega? pregunto ahqq"                                                                                                        
##  [2] "Beije minha boca e diz que tem dislexia #broxante"                                                                                         
##  [3] "tenho uma leve dislexia"                                                                                                                   
##  [4] "eu devo ter dislexia certeza"                                                                                                              
##  [5] "A câmera do iPhone tipo eh dislexia pq eh do lado errado a sai a foto"                                                                     
##  [6] "@caiohot minha dislexia n gostou do nome hsusbsus"                                                                                         
##  [7] "Eh dislexia\n\nDormir hoje*"                                                                                                               
##  [8] "Matheus vou escrever um relato apesar de eu ter dislexia um suplício minha amiga estava sendo velada e entrou no meu carro.  #relatoaovivo"
##  [9] "De vez em quando penso se tenho um pouco de dislexia pois troco as letras das palavras."                                                   
## [10] "@reginakadov Eu dou um desconto pq ela tem dislexia e se perde maaaaas ela é &lt;3"
##função "getUser": obtem informações dos usuários com a função "getUser"
##função "str": examina o conteúdo do resultado.
###USUÁRIO ESCOLHIDO: INSTITUTO ABCD (OSCIP paulista que estuda transtornos de aprendizagem)

iABCD_user <- getUser('InstitutoABCD')
str(iABCD_user)
## Reference class 'user' [package "twitteR"] with 18 fields
##  $ description      : chr "https://t.co/XQqR0nkoDx https://t.co/xvZ49avFqr"
##  $ statusesCount    : num 691
##  $ followersCount   : num 724
##  $ favoritesCount   : num 0
##  $ friendsCount     : num 1353
##  $ url              : chr "http://t.co/xVGG2JGBe4"
##  $ name             : chr "InstitutoABCD"
##  $ created          : POSIXct[1:1], format: "2011-12-15 23:45:59"
##  $ protected        : logi FALSE
##  $ verified         : logi FALSE
##  $ screenName       : chr "InstitutoABCD"
##  $ location         : chr "São Paulo, Brasil"
##  $ lang             : chr "pt"
##  $ id               : chr "437899798"
##  $ lastStatus       :Reference class 'status' [package "twitteR"] with 17 fields
##   ..$ text         : chr "Acesse a página do evento para mais informações e compra de ingressos: https://t.co/jU7IEnSV4L #TEAp #IABCD htt"| __truncated__
##   ..$ favorited    : logi FALSE
##   ..$ favoriteCount: num 0
##   ..$ replyToSN    : chr(0) 
##   ..$ created      : POSIXct[1:1], format: "2017-08-31 20:20:12"
##   ..$ truncated    : logi FALSE
##   ..$ replyToSID   : chr(0) 
##   ..$ id           : chr "903351739746848772"
##   ..$ replyToUID   : chr(0) 
##   ..$ statusSource : chr "<a href=\"http://www.hootsuite.com\" rel=\"nofollow\">Hootsuite</a>"
##   ..$ screenName   : chr "Unknown"
##   ..$ retweetCount : num 0
##   ..$ isRetweet    : logi FALSE
##   ..$ retweeted    : logi FALSE
##   ..$ longitude    : chr(0) 
##   ..$ latitude     : chr(0) 
##   ..$ urls         :'data.frame':    1 obs. of  5 variables:
##   .. ..$ url         : chr "https://t.co/jU7IEnSV4L"
##   .. ..$ expanded_url: chr "http://ow.ly/LJkx30eGrpi"
##   .. ..$ display_url : chr "ow.ly/LJkx30eGrpi"
##   .. ..$ start_index : num 71
##   .. ..$ stop_index  : num 94
##   ..and 53 methods, of which 39 are  possibly relevant:
##   ..  getCreated, getFavoriteCount, getFavorited, getId, getIsRetweet,
##   ..  getLatitude, getLongitude, getReplyToSID, getReplyToSN,
##   ..  getReplyToUID, getRetweetCount, getRetweeted, getRetweeters,
##   ..  getRetweets, getScreenName, getStatusSource, getText, getTruncated,
##   ..  getUrls, initialize, setCreated, setFavoriteCount, setFavorited,
##   ..  setId, setIsRetweet, setLatitude, setLongitude, setReplyToSID,
##   ..  setReplyToSN, setReplyToUID, setRetweetCount, setRetweeted,
##   ..  setScreenName, setStatusSource, setText, setTruncated, setUrls,
##   ..  toDataFrame, toDataFrame#twitterObj
##  $ listedCount      : num 6
##  $ followRequestSent: logi FALSE
##  $ profileImageUrl  : chr "http://pbs.twimg.com/profile_images/842431055323910144/N02JNWj1_normal.jpg"
##  and 59 methods, of which 45 are  possibly relevant:
##    getCreated, getDescription, getFavorites, getFavoritesCount,
##    getFavouritesCount, getFollowerIDs, getFollowers, getFollowersCount,
##    getFollowRequestSent, getFriendIDs, getFriends, getFriendsCount, getId,
##    getLang, getLastStatus, getListedCount, getLocation, getName,
##    getProfileImageUrl, getProtected, getScreenName, getStatusesCount,
##    getUrl, getVerified, initialize, setCreated, setDescription,
##    setFavoritesCount, setFollowersCount, setFollowRequestSent,
##    setFriendsCount, setId, setLang, setLastStatus, setListedCount,
##    setLocation, setName, setProfileImageUrl, setProtected, setScreenName,
##    setStatusesCount, setUrl, setVerified, toDataFrame,
##    toDataFrame#twitterObj
##Obtendo 100 tweets da timeline, posteriormente, criando um banco de dados

iABCD_timeline <- userTimeline('InstitutoABCD', n = 100)
df.timeline <- twListToDF(iABCD_timeline)
df.timeline$text[1:10]
##  [1] "Acesse a página do evento para mais informações e compra de ingressos: https://t.co/jU7IEnSV4L #TEAp #IABCD https://t.co/fTc5fMVECs"       
##  [2] "Por meio do “Mães de MT”, nasceu o “Dislexia MT”. Vem conhecer: https://t.co/piv8n7K4Wq #TEAp #IABCD https://t.co/hqJngjezGL"              
##  [3] "Você sabe a diferença? https://t.co/EBljKbpDHT #TEAp #IABCD #dislexia https://t.co/gnuKo0lU1S"                                             
##  [4] "O escritor disléxico e alfabetizado aos 9 anos que estreará na Bienal do Livro Rio: https://t.co/Kt571gkQFb #TEAp… https://t.co/IRkEzCs2of"
##  [5] "DOWNLOAD GRATUITO! Entendendo o Desenvolvimento Infantil: https://t.co/pJY9GGQsgd #TEAp #IABCD https://t.co/6U2Ym8APiX"                    
##  [6] "Campanha da @assembleiamt divulga desafios de pessoas com #dislexia. https://t.co/FZE0005vzk #TEAp #IABCD https://t.co/co3bzjjB6y"         
##  [7] "O informativo de escola que mudou a vida de um #disléxico. https://t.co/zydbMotkvk #TEAp #IABCD https://t.co/2qiOjNfeah"                   
##  [8] "DOWNLOAD GRATUITO! Entendendo o Desenvolvimento Infantil: https://t.co/mvU0J1nxIS #TEAp #IABCD https://t.co/ADQyCtncEb"                    
##  [9] "O que os cientistas brasileiros estão investigando sobre memória e atividade cerebral? https://t.co/RWPm3i72SV… https://t.co/auZu6ADmvM"   
## [10] "@anapaulaxongani fala sobre a #dislexia de um jeito divertido: https://t.co/mTfzsm7LUO #TEAp #IABCD https://t.co/E4CSOg6Sza"

Parte2 - Construir uma visualização interessante com os dados capturados.

Orientação: Não é preciso seguir nenhuma instrução específica e você pode utilizar sua criatividade. Utilize o tutorial sobre captura dados no twitter como apoio (https://github.com/leobarone/mq_ufmg_17/blob/master/mq_ufmg_2017_tutorial9.Rmd). OBS.: não se preocupe em enviar as “keys” de sua conta de desenvolvedor, pois posso inserir as minhas ao corrigir sua atividade.

##Usando a abordagem "tidy" para texto

###Pacotes necessários
library(tidytext)
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:twitteR':
## 
##     id, location
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)
library(tidyr)
library(magrittr)
## 
## Attaching package: 'magrittr'
## The following object is masked from 'package:tidyr':
## 
##     extract
library(tm)
## Loading required package: NLP
## 
## Attaching package: 'NLP'
## The following object is masked from 'package:ggplot2':
## 
##     annotate
## The following object is masked from 'package:httr':
## 
##     content
library(wordcloud)
## Loading required package: RColorBrewer
##Criando um banco de dados com os tweets e utilizando a função de tokenização de texto
tweets_df <- data_frame(tweets_dis = 1:length(df.tweets_noret$text), 
                          text = df.tweets_noret$text)

tweets_token <- tweets_df %>%
  unnest_tokens(word, text)
glimpse(tweets_token)
## Observations: 4,875
## Variables: 2
## $ tweets_dis <int> 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, ...
## $ word       <chr> "la", "dislexia", "se", "pega", "pregunto", "ahqq",...
##Apontando as palavras do português sem significado e criando um banco de dados
stopwords_pt <- c(stopwords("pt"), "que", "a", "de", "q", 
                  "na", "com", "o", "e", "t.co", "pra")
stopwords_pt_df <- data.frame(word = stopwords_pt)

##Função anti_join: mantemos apenas as palavras que não estao em "stopwords_pt_df"

tweets_token <- tweets_token %>%
  anti_join(stopwords_pt_df, by = "word")
## Warning: Column `word` joining character vector and factor, coercing into
## character vector
##Função count: apresenta a frequência de palavras
##Construindo um gráfico de barras dos temos mais frequentes
tweets_token %>%
  count(word, sort = TRUE) %>%
  filter(n > 10) %>%
  mutate(word = reorder(word, n)) %>%
  ggplot(aes(word, n)) +
    geom_col() +
    xlab(NULL) +
    coord_flip()

##Função wordcloud: cria uma nuvem de palavras

tweets_token %>%
  count(word, sort = TRUE) %>%
  with(wordcloud(word, n, max.words = 100))

##Observando a ocorrência conjunta de termos: NÃO HÁ
tweets_bigrams <- tweets_df %>%
  unnest_tokens(bigram, text, token = "ngrams", n = 2)
tweets_bigrams %>%
  count(bigram, sort = TRUE)
## # A tibble: 3,476 x 2
##            bigram     n
##             <chr> <int>
##  1     https t.co    81
##  2     a dislexia    52
##  3 minha dislexia    37
##  4    de dislexia    29
##  5 tenho dislexia    28
##  6    da dislexia    22
##  7   tem dislexia    22
##  8    dislexia ã©    17
##  9     dislexia e    16
## 10       eu tenho    16
## # ... with 3,466 more rows