2014년 10월 26일 일요일

[성공] Twitter + R + Mavericks + WordCloud



# installed the newest version of the twitteR package from github.

install.packages(c("devtools", "rjson", "bit64", "httr"))

#RESTART R session!

library(devtools)
install_github("twitteR", username="geoffjentry")
library(twitteR)


#
api_key <- "YOUR API KEY"
api_secret <- "YOUR API SECRET"
access_token <- "YOUR ACCESS TOKEN"
access_token_secret <- "YOUR ACCESS TOKEN SECRET"

setup_twitter_oauth(api_key,api_secret,access_token,access_token_secret)


#
searchTwitter("iphone")


Step 1: Load all the required packages
library(twitteR)
library(tm)
library(wordcloud)
library(RColorBrewer)

Step 2: Let's get some tweets in english containing the words "machine learning"
mach_tweets = searchTwitter("machine learning", n=500, lang="en")


Step 3: Extract the text from the tweets in a vector
mach_text = sapply(mach_tweets, function(x) x$getText())


Step 4: Construct the lexical Corpus and the Term Document Matrix
We use the functionCorpus to create the corpus, and the functionVectorSource to indicate that the text is in the character vector mach_text. In order to create the term-document matrix we apply different transformation such as removing numbers, punctuation symbols, lower case, etc.
# create a corpus
mach_corpus = Corpus(VectorSource(mach_text))

# create document term matrix applying some transformations
tdm = TermDocumentMatrix(mach_corpus,
   control = list(removePunctuation = TRUE,
   stopwords = c("machine", "learning", stopwords("english")),
   removeNumbers = TRUE, tolower = TRUE))


Step 5: Obtain words and their frequencies
# define tdm as matrix
m = as.matrix(tdm)
# get word counts in decreasing order
word_freqs = sort(rowSums(m), decreasing=TRUE) 
# create a data frame with words and their frequencies
dm = data.frame(word=names(word_freqs), freq=word_freqs)


Step 6: Let's plot the wordcloud
# plot wordcloud
wordcloud(dm$word, dm$freq, random.order=FALSE, colors=brewer.pal(8, "Dark2"))

# save the image in png format
png("MachineLearningCloud.png", width=12, height=8, units="in", res=300)
wordcloud(dm$word, dm$freq, random.order=FALSE, colors=brewer.pal(8, "Dark2"))
dev.off()

댓글 없음:

댓글 쓰기