Thursday, October 25, 2012

Exploring R Local Server for Viewing d3 examples

Recently there was a great post on javascript and d3 for R users. The post showed a simple way to get a local server going using the python command (python -m SimpleHTTPServer 8888 &). A local server is needed to view the d3 examples in some cases. I was curious to see if I can view those using the internal R server.

I looked at googleVis package since they generate plots using the R local server. I tried to use the following code adapted from plot.gvis method in googlevis package and see if I could view the d3 examples.

# directory where d3 files were downloaded from github
setwd("~/javascript/d3github")

# piece of code adapted from plot.gvis method in googleVis package
tools:::startDynamicHelp()
## Error: server already running

googlevis.httpd.handler <- function(path, query, ...) {
    path <- gsub("^/custom/googleVis/", "", path)
    f <- sprintf("%s%s%s", getwd(), .Platform$file.sep, path)
    list(file = f, `content-type` = "text/html;charset=utf-8", `status code` = 200L)
}

env <- get(".httpd.handlers.env", asNamespace("tools"))
env[["googleVis"]] <- googlevis.httpd.handler

# viewing the html files through local server

baseURL <- sprintf("http://127.0.0.1:%s/custom/googleVis/examples/contour/contour.html", 
    tools:::httpdPort)
browseURL(baseURL)

baseURL <- sprintf("http://127.0.0.1:%s/custom/googleVis/examples/bubble/bubble.html", 
    tools:::httpdPort)
browseURL(baseURL)

baseURL <- sprintf("http://127.0.0.1:%s/custom/googleVis/examples/choropleth/choropleth.html", 
    tools:::httpdPort)
browseURL(baseURL)

The examples contour.html and bubble.html work fine. But choropleth.html does not render the colors properly. I don't know why that is happening.

However, if the server is already started with the python command, then from within R just the following commands work great

# server started with python command in command prompt in the directory
# ~/javascript/d3github python -m SimpleHTTPServer 8000

baseURL = "http://localhost:8000/examples/contour/contour.html"
browseURL(baseURL)

baseURL = "http://localhost:8000/examples/bubble/bubble.html"
browseURL(baseURL)

baseURL = "http://localhost:8000/examples/choropleth/choropleth.html"
browseURL(baseURL)

If anybody has other quicker ways of starting the R local server, please let me know.

Sunday, October 14, 2012

Statistics Courses using R in Coursera

Coursera offers free online courses offered by top universities. Upcoming in those are some statistics courses all of which use R primarily as the language.