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!

installing R 2.13.1 on Amazon EC2’s “Amazon Linux” AMI #rstats

Condensed from this post (and comments) on David Chudzicki’s blog, tweaked, and updated for R-2.13.1.

Assumes you’re starting with a virgin “Amazon Linux” AMI. I picked “Basic 64-bit Amazon Linux AMI 2011.02.1 Beta” (AMI Id: ami-8e1fece7) because it was marked as free tier eligible on the “Quick Start” tab of AWS’s “Launch Instance” dialog box:

$ sudo yum -y install make libX11-devel.* libICE-devel.* libSM-devel.* libdmx-devel.* libx* xorg-x11* libFS* libX*  readline-devel gcc-gfortran gcc-c++ texinfo tetex

$ wget http://cran.r-project.org/src/base/R-2/R-2.13.1.tar.gz

$ tar zxf R-2.13.1.tar.gz && cd R-2.13.1
$ ./configure && make

$ # make coffee... or finish your PhD thesis... (yes, it takes that long)
[...]
$ # finally, if all is well:

$ sudo make install

$ cd
$ R --version
R version 2.13.1 (2011-07-08)
Copyright (C) 2011 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Platform: x86_64-unknown-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under the terms of the
GNU General Public License version 2.
For more information about these matters see

http://www.gnu.org/licenses/.

As always, refer to the Installation and Administration manual for details and options.

If you want to install RCurl, or anything which depends on it like twitteR, you’ll need to install libcurl & friends first:

$ sudo yum -y install libcurl libcurl-devel

slides from my R tutorial on Twitter text mining #rstats

Update: An expanded version of this tutorial will appear in the new Elsevier book Practical Text Mining and Statistical Analysis for Non-structured Text Data Applications by Gary Miner et. al which is now available for pre-order from Amazon.

In conjunction with the book, I have cleaned up the tutorial code and published it on github.


Last month I presented this introduction to R at the Boston Predictive Analytics MeetUp on Twitter Sentiment.

The goal of the presentation was to expose a first-time (but technically savvy) audience to working in R. The scenario we work through is to estimate the sentiment expressed in tweets about major U.S. airlines. Even with a tiny sample and a very crude algorithm (simply counting the number of positive vs. negative words), we find a believable result. We conclude by comparing our result with scores we scrape from the American Consumer Satisfaction Index web site.

Jeff Gentry’s twitteR package makes it easy to fetch the tweets. Also featured are the plyr, ggplot2, doBy, and XML packages. A real analysis would, no doubt, lean heavily on the tm text mining package for stemming, etc.

Here is the slimmed-down version of the slides:

And here’s a PDF version to download.

Special thanks to John Verostek for putting together such an interesting event, and for providing valuable feedback and help with these slides.


Update: thanks to eagle-eyed Carl Howe for noticing a slightly out-of-date version of the score.sentiment() function in the deck. Missing was handling for NA values from match(). The deck has been updated and the code is reproduced here for convenience:


score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
{
	require(plyr)
	require(stringr)
	
	# we got a vector of sentences. plyr will handle a list
	# or a vector as an "l" for us
	# we want a simple array ("a") of scores back, so we use 
	# "l" + "a" + "ply" = "laply":
	scores = laply(sentences, function(sentence, pos.words, neg.words) {
		
		# clean up sentences with R's regex-driven global substitute, gsub():
		sentence = gsub('[[:punct:]]', '', sentence)
		sentence = gsub('[[:cntrl:]]', '', sentence)
		sentence = gsub('\\d+', '', sentence)
		# and convert to lower case:
		sentence = tolower(sentence)

		# split into words. str_split is in the stringr package
		word.list = str_split(sentence, '\\s+')
		# sometimes a list() is one level of hierarchy too much
		words = unlist(word.list)

		# compare our words to the dictionaries of positive & negative terms
		pos.matches = match(words, pos.words)
		neg.matches = match(words, neg.words)
	
		# match() returns the position of the matched term or NA
		# we just want a TRUE/FALSE:
		pos.matches = !is.na(pos.matches)
		neg.matches = !is.na(neg.matches)

		# and conveniently enough, TRUE/FALSE will be treated as 1/0 by sum():
		score = sum(pos.matches) - sum(neg.matches)

		return(score)
	}, pos.words, neg.words, .progress=.progress )

	scores.df = data.frame(score=scores, text=sentences)
	return(scores.df)
}

Hype isn’t limited to IT vendors: presenting my new Turbo Force High Velocity Circulator

I went to the store to purchase a small fan to blow nice cool air towards my desk. But when I got it home and took a closer look, it turns out that I had selected an HT-900 Turbo Force® Air Circulator Fan from Honeywell.

Honeywell, eh? They make jet engines and ammonium nitrate fertilizer which won’t blow up! Maybe there’s more to this fan than I realized.

Intruiged, I started to read the Owner’s Manual:

The Turbo Force® High Velocity Air Circulator Fans are aerodynamically designed to give you the versatility of changing this fan’s angular direction simply by adjusting the fan to ANY desired angular output (Fig.1).

I think that means: It tilts.

The introduction continues:

Upon using this fan, you will feel a strong and powerful air stream that will quickly move air in order to cool an area rapidly and efficiently.

Translation: Turn it on and it will blow air.

Suddenly all that vendor verbiage about how cloud computing will increase the synergies between your technology and business priorities sounds… well… not that bad. At least they’re not hyping something as simple as a desk fan.

googleVis-0.2.4 requires older version of RJSONIO (0.5-0) #rstats

[Update: the new release of googleVis accounts for changes in RJSONIO's handling of backslashes, so you probably won't need the older version.]

Something has apparently changed in the way RJSON’s toJSON() function works which is causing all sorts of extra escape characters (backslashes) to appear in the googleVis-generated JavaScript, at least when trying to set a visualization’s initial state. This bogus code causes the browser’s JavaScript engine to choke just before it can call chart.draw(), so you don’t see the Flash visualization at all–just a blank space with the pretty footer.

This is at least the case on Mac OS 10.6.7 and Markus Gesmann gets all the credit for tracking it down.

Here’s an example state string which selects a couple of bubbles to be labeled (“Oranges” and “Apples”) and sets the time to start about half-way through:

state.json='{"xAxisOption":"3","xZoomedDataMin":81,"playDuration":15000,"sizeOption":"_UNISIZE","xZoomedDataMax":111,"xLambda":1,"dimensions":{"iconDimensions":["dim0"]},"yZoomedDataMax":91,"duration":{"multiplier":1,"timeUnit":"Y"},"orderedByX":false,"xZoomedIn":false,"yZoomedDataMin":71,"showTrails":false,"orderedByY":false,"iconType":"BUBBLE","uniColorForNonSelected":false,"yZoomedIn":false,"nonSelectedAlpha":0.4,"yLambda":1,"time":"2010","yAxisOption":"4","iconKeySettings":[{"LabelY":27,"key":{"dim0":"Apples"},"LabelX":42}],"colorOption":"6"}'

# create the motion chart
M=gvisMotionChart(Fruits, "Fruit", "Year", options=list(state=state.json))

Here’s the output in question using the current RJSONIO 0.7:

> cat(M$html$chart['jsDrawChart'])

// jsDrawChart
function drawChartMotionChartID6db280db() {
  var data = gvisDataMotionChartID6db280db()
  var chart = new google.visualization.MotionChart(
   document.getElementById('MotionChartID6db280db')
  );
  var options ={};
options["width"] = [    600 ];
options["height"] = [    500 ];
options["state"] = [ "{\\"xAxisOption\\":\\"3\\",\\"xZoomedDataMin\\":81,\\"playDuration\\":15000,\\"sizeOption\\":\\"_UNISIZE\\",\\"xZoomedDataMax\\":111,\\"xLambda\\":1,\\"dimensions\\":{\\"iconDimensions\\":[\\"dim0\\"]},\\"yZoomedDataMax\\":91,\\"duration\\":{\\"multiplier\\":1,\\"timeUnit\\":\\"Y\\"},\\"orderedByX\\":false,\\"xZoomedIn\\":false,\\"yZoomedDataMin\\":71,\\"showTrails\\":false,\\"orderedByY\\":false,\\"iconType\\":\\"BUBBLE\\",\\"uniColorForNonSelected\\":false,\\"yZoomedIn\\":false,\\"nonSelectedAlpha\\":0.4,\\"yLambda\\":1,\\"time\\":\\"2010\\",\\"yAxisOption\\":\\"4\\",\\"iconKeySettings\\":[{\\"LabelY\\":27,\\"key\\":{\\"dim0\\":\\"Apples\\"},\\"LabelX\\":42}],\\"colorOption\\":\\"6\\"}" ];
  chart.draw(data,options);
}

And here’s working code from RJSONIO 0.5:

> cat(M$html$chart['jsDrawChart'])

// jsDrawChart
function drawChartMotionChartID47a55df7() {
  var data = gvisDataMotionChartID47a55df7()
  var chart = new google.visualization.MotionChart(
   document.getElementById('MotionChartID47a55df7')
  );
  var options ={};
options["width"] =    600;
options["height"] =    500;
options["state"] = "{\"sizeOption\":\"5\",\"nonSelectedAlpha\":0.4,\"xLambda\":1,\"iconType\":\"BUBBLE\",\"yZoomedDataMax\":91,\"iconKeySettings\":[{\"LabelY\":-124,\"LabelX\":-160,\"key\":{\"dim0\":\"Oranges\"}},{\"LabelY\":53,\"LabelX\":37,\"key\":{\"dim0\":\"Apples\"}}],\"xZoomedIn\":false,\"orderedByX\":false,\"showTrails\":false,\"yZoomedIn\":false,\"yZoomedDataMin\":71,\"xZoomedDataMin\":81,\"orderedByY\":false,\"xAxisOption\":\"3\",\"yAxisOption\":\"4\",\"uniColorForNonSelected\":false,\"duration\":{\"timeUnit\":\"Y\",\"multiplier\":1},\"time\":\"2009\",\"yLambda\":1,\"xZoomedDataMax\":111,\"dimensions\":{\"iconDimensions\":[\"dim0\"]},\"colorOption\":\"2\",\"playDuration\":15000}";
  chart.draw(data,options);
}

Maybe this post can help others avoid the blank look I had on my face as I kept staring at a blank page in my browser.

quantmod makes it easy to watch silver prices crash in R #rstats

As if there hasn’t been enough going on this week, silver prices have fallen nearly $10 per ounce. That’s a reduction of over 20%. Jeffrey Ryan’s quantmod package makes it easy to download the latest prices from OANDA’s web site and plot the excitement.

The getSymbols() function is at the heart of quantmod’s data retrieval prowess, currently handling Yahoo! Finance, Google Finance, the St. Louis Fed’s FRED, and OANDA sites, in addition to MySQL databases and RData and CSV files.

First a word of warning: if you have a computer science background, you may cringe at the way getSymbols() returns data. Rather than returning the fetched data as the result of a function call, it populates your R session’s .GlobalEnv environment (or another one of your choosing via the env parameter) with xts and zoo objects containing your data. For example, if you ask for IBM’s stock prices via getSymbols("IBM"), you will find the data in a new “IBM” object in your .GlobalEnv. This behavior can be changed by setting auto.assign=F, but then you can only request one symbol at a time. But this is a minor nit about an incredibly useful package.

There’s even a wrapper function to help retrieve precious metal prices, and we will use this getMetals() function to retrieve the last year’s worth of prices for gold (XAU) and silver (XAG):

library(quantmod)
getMetals(c('XAU', 'XAG'), from=Sys.Date()-365)

Yup — that’s it. getMetals() lets us know it has created two new objects:

[1] "XAUUSD" "XAGUSD"

There were also few warning messages complaining about the last line in the downloaded file. I haven’t bothered to dig into it as the data seem fine, including today’s price:

> ls()
[1] "XAGUSD" "XAUUSD"

> head(XAGUSD)
           XAG.USD
2010-05-07 17.6600
2010-05-08 18.4600
2010-05-09 18.4320
2010-05-10 18.4336
2010-05-11 18.5400
2010-05-12 19.3300

> tail(XAGUSD)
           XAG.USD
2011-05-02 47.9850
2011-05-03 45.2373
2011-05-04 44.0238
2011-05-05 40.9171
2011-05-06 37.9939
2011-05-07 35.0598

And here’s how easy it is to use the package’s built-in graphing facilities:

chartSeries(XAUUSD, theme="white")

chartSeries(XAGUSD, theme="white")

Yup — that’s quite a shellacking for silver.

Now I tend to be a ggplot2 guy myself, and I have never actually worked with xts or zoo objects before, but it’s pretty easy to get them into a suitable data.frame:

silver = data.frame(XAGUSD)
silver$date = as.Date(rownames(silver))
colnames(silver)[1] = 'price'

library(ggplot2)
ggplot(data=silver, aes(x=date, y=price)) + geom_line() + theme_bw()

Slides: “Accessing Databases from R” #rstats

For the past few meetings of the Greater Boston useR Group, we have been opened with an introductory “useR Vignette” talk on a topic which may be helpful for new R users. This week, I presented an overview of accessing databases from R. Several people have tweeted and blogged nice things about my talk
and have asked for the slides, so here they are, via Slideshare:

The final slide includes the code which I used to create and populate the ‘testdb’ database I used for my examples. I have duplicated it here as it’s a nice, quick example of using DBI to store an R data.frame in a database:

First, create new database & user in MySQL:

mysql> create database testdb;
mysql> grant all privileges on testdb.* to 'testuser'@'localhost' identified by 'testpass';
mysql> flush privileges;

In R, load the “mtcars” data.frame, clean it up, and write it to a new “motortrend” table:

library(stringr)
library(RMySQL)

data(mtcars)

# car name is data.frame's rownames. Let's split into manufacturer and model columns:
mtcars$mfg = str_split_fixed(rownames(mtcars), ' ', 2)[,1]
mtcars$mfg[mtcars$mfg=='Merc'] = 'Mercedes'
mtcars$model = str_split_fixed(rownames(mtcars), ' ', 2)[,2]

# connect to local MySQL database (host='localhost' by default)
con = dbConnect("MySQL", "testdb", username="testuser", password="testpass")

dbWriteTable(con, 'motortrend', mtcars)

dbDisconnect(con)
Follow

Get every new post delivered to your Inbox.

Join 58 other followers