Uncategorised

How to create a Twitter word cloud?

If you want to create a word cloud you have to request the access to the Twitter API. For this simply go to Twitter Apps and sign in.

  1. Click on the “Create New App” Button.
  2. Fill in the Application Details
    1. Name: Give you App a unique name
    2. Description: Quickly describe your App
    3. Website: Fill in the URL of your Website or Blog or leave a placeholder if you don’t have either.
    4. Callback URL: http://127.0.0.1:1410 this URL will redirect you after the authentication
  3. Go to Keys and Access Tokens and find the Consumer Key and Secret Consumer Key

Insert the key into the following R-Code and let it run step by step.

install.packages(c("wordcloud", "twitteR", "tm"))
library(twitteR)
library(wordcloud)
library(tm)

# Insert your Key and the secret Key here
twitter_key <- "Key"
twitter_secret <- "Secret_Key"

# The Browser will open and you can give permission to your App
oauth<-setup_twitter_oauth(twitter_key, twitter_secret)

# Insert the Twitter profile and the amount of Tweets
myTweets<-userTimeline("Uber", n=100)

str(myTweets[[1]])

tweetTexts<-unlist(lapply(myTweets, function(t) { t$text}))
tweetTexts <- sapply(tweetTexts, function(x) iconv(enc2utf8(x), sub = "byte"))

# Create a corpus
corpus <-  Corpus(VectorSource(tweetTexts))

# Apply some transformations
tdm <-  TermDocumentMatrix(corpus,
                         control = list(removePunctuation = TRUE,
                                        removeNumbers = TRUE, tolower = TRUE))


m = as.matrix(tdm)
word_freqs = sort(rowSums(m), decreasing=TRUE) 
dm = data.frame(word=names(word_freqs), freq=word_freqs)

# plot wordcloud
wordcloud(dm$word, dm$freq, random.order=FALSE, colors=brewer.pal(8, "Dark2"))

This code creates the following word cloud:

Have fun and alter the code as you like.

 

For this post I used the following sources:

R-Bloggers, Google

Leave a Reply

Your email address will not be published. Required fields are marked *