One-liners which make me love R: twitteR’s searchTwitter() #rstats

R reminds me a lot of English. It’s easy to get started, but very difficult to master. So for all those times I’ve spent… well, forever… trying to figure out the “R way” of doing something, I’m glad to share these quick wins.

My recent R tutorial on mining Twitter for consumer sentiment wouldn’t have been possible without Jeff Gentry’s amazing twitteR package (available on CRAN). It does so much of the behind-the-scenes heavy lifting to access Twitter’s REST APIs, that one line of code is all you need to perform a search and retrieve the (even paginated) results:

library(twitteR)

tweets = searchTwitter("#rstats", n=1500)

You can search for anything, of course, “#rstats” is just an example. (And if you’re really into that hashtag, the twitteR package even provides an Rtweets() function which hardcodes that search string for you.) The n=1500 specifies the maximum number of tweets supported by the Search API, though you may retrieve fewer as Twitter’s search indices contain only a couple of days’ tweets.

What you get back is a list of tweets (technically “status updates”):

> head(tweets)
[[1]]
[1] "Cloudnumberscom: CloudNumbers.com \023 #Rstats gets real in the cloud http://t.co/Vw4Gupr via @AddToAny"

[[2]]
[1] "0_h_r_1: CloudNumbers.com \023 #Rstats gets real in the cloud via DecisionStats - I came across Cloudnumbers.com . ... http://tinyurl.com/5sjagjg"

[[3]]
[1] "cmprsk: RT I just joined the beta to run #Rstats in the cloud with cloudnumbers.com http://t.co/lvVp0YJ via @cloudnumberscom http://bit.ly/lbSruR"

[[4]]
[1] "0_h_r_1: I just joined the beta to run #Rstats in the cloud with cloudnumbers.com http://t.co/lvVp0YJ via @cloudnumberscom"

[[5]]
[1] "cmprsk: RT man, the #rstats think people I am too soft on #sas, the #sas people think I am too soft on #wps, the #wps pe... http://bit.ly/innEv8"

[[6]]
[1] "keepstherainoff: Thanks to @cmprsk @geoffjentry and @MikeKSmith for colour-coded #Rstats GUI advice"

> class(tweets[[1]])
[1] "status"
attr(,"package")
[1] "twitteR"

Now that you have some tweets, the fun really begins. To get you started, the status class includes a very handy toDataFrame() accessor method (see ?status):

> library(plyr) 
> tweets.df = ldply(tweets, function(t) t$toDataFrame() )

> str(tweets.df)
'data.frame':	131 obs. of  10 variables:
 $ text        : Factor w/ 122 levels "CloudNumbers.com \023 #Rstats gets real in the cloud http://t.co/Vw4Gupr via @AddToAny",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ favorited   : logi  NA NA NA NA NA NA ...
 $ replyToSN   : logi  NA NA NA NA NA NA ...
 $ created     : POSIXct, format: "2011-07-04 13:50:39" "2011-07-04 13:48:10" "2011-07-04 13:29:00" "2011-07-04 13:23:42" ...
 $ truncated   : logi  FALSE FALSE FALSE FALSE FALSE FALSE ...
 $ replyToSID  : logi  NA NA NA NA NA NA ...
 $ id          : Factor w/ 131 levels "87941406873751552",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ replyToUID  : logi  NA NA NA NA NA NA ...
 $ statusSource: Factor w/ 17 levels "<a href="http://twitter.com/tweetbutton" rel="nofollow">Tweet Button</a>",..: 1 2 3 1 3 4 5 5 3 4 ...
 $ screenName  : Factor w/ 64 levels "Cloudnumberscom",..: 1 2 3 2 3 4 2 5 3 6 ...

You can pull a particular user’s tweets just as easily with the userTimeline() function. Heck, the package even lets you tweet from R if you use Jeff’s companion ROAuth package, but that requires more than one line….

Enjoy!

Posted in One-liners. Tags: , . 6 Comments »

One-liners which make me love R: Make your data dance (Hans Rosling style) with googleVis #rstats

It may be a cliché, but much of R’s utility comes from its amazing community. And by community, I am specifically referring to the bright, hard-working people who are willing to share their knowledge and code with the rest of us. Because of their contributions, we can do some amazingly cool and useful things with very little code of our own. It is in this context that I launch this new series to highlight packages and functions which make it easy to do jaw-droppingly cool and useful things.

First up: the googleVis package by Markus Gesmann and Diego de Castillo which makes it easy — often with just one-line of R — to harness the Google Visualization API. Annotated timelines, gauges, maps, org charts, tree maps, and more are suddenly at your command.

I’m going to focus on the motion chart, popularized by Hans Rosling in his groundbreaking 2006 TED talk on global economic development. (If you haven’t seen it yet, you should. Right now. Seriously. Go.) Motion charts are an innovative way to display multidimensional time series in an interactive way. And the googleVis package even comes with some sample data to make it even easier to try them out.

The package is available from CRAN if you need to install it.

To get started, load the package and the included “Fruits” data.frame:

library(googleVis)
data(Fruits)

This data.frame contains some sample data about sales of various fruits at different locations for different years. There’s even a proper Date column already constructed for us from the numeric Year column:

To make the chart, we need to give the gvisMotionChart() function our data.frame and tell it a few things about it: the column which identifies the items to examine (idvar=Fruit), the time dimension (timevar=Date), and optionally a name to use to identify the chart in the generated HTML and JavaScript (we’ll use chartid="ILoveFruits"):

M = gvisMotionChart(data=Fruits, idvar="Fruit", timevar="Date", chartid="ILoveFruit")

That’s it.

You can view your chart with the overridden plot() function. It will automatically spawn a browser window and serve up your chart through R’s internal web server:

plot(M)

Since WordPress doesn’t allow embedded JavaScript, please click through to see the motion chart in action:

You can also access all 165 lines of the generated HTML and JavaScript and save it to disk:

cat(unlist(M$html), file="output/ILoveFruits.html")

Time suck alert: googleVis may make them easy to create, but motion charts can be a lot of fun to play with. You have been warned…

If you want to take a look at an example with some real data, you might be interested in the 20 Years of the U.S. Domestic Airline Market In 20 seconds post on my work blog.

Finally, here are the slides from my lightning talk on this topic at this month’s Greater Boston useR Group meeting:

Have fun!

Follow

Get every new post delivered to your Inbox.

Join 62 other followers