My first examples with knitr

Let’s include some simple R code:

1+2
## [1] 3

That worked.

Let’s include a plot:

df <- data.frame(x=1:10, y=1:10)
plot(y ~ x, data=df, pch=19, col="blue")

Nice.

Now let’s insert an interactive chart with googleVis:

## load the googleVis package
suppressPackageStartupMessages(library(googleVis))
## create the scatter chart
sc <- gvisScatterChart(data=df,
                        options=list(width=300, height=300, 
                                     legend='none',
                                     hAxis="{title:'x'}",
                                     vAxis="{title:'y'}")

          )

The output of gvisScatterChart is a complete web page, including <html> and <body> tags, but here I only need the chart itself which is stored in sc$html$chart. To include the chart in the output we have to set the result parameter for the code chunk to ‘asis’, or otherwise the html code generated by googleVis will be displayed as a string.

## {r results='asis'}
print(sc, 'chart') ## same as cat(sc$html$chart)

Hurray, it works! Hover over the dots to get more information about the values. I am sure this could be simplified further in the same way that I can use ggplot2 and lattice plots without the explicit print statement.

Next, let’s create a geo chart:

geo <- gvisGeoChart(CityPopularity, locationvar='City', 
                  colorvar='Popularity',
                    options=list(region='US', height=350, 
                                   displayMode='markers',
               colorAxis="{colors: ['orange','blue']}") )
print(geo, 'chart')

Wonderful!

Unfortunately for charts which still rely on Flash, such as gvisMotionChart, gvisAnnotatedTimeLine and gvisGeoMap, the preview browser of RStudio will not display those charts at the moment. You have to open the output html-file in your system browser. But that is easy, just hit the browser button in the preview window, circled in red below.

RStudio preview window

Additionally you may have to add your working directory to the trusted location in the global secturity settings of your Flash Player.

Here is a little motion chart example:

M <- gvisMotionChart(Fruits, "Fruit", "Year",
                     options=list(width=550, height=450))
print(M, 'chart')

Conclusion

RStudio and knitr might be the way forward to create quick analysis reports.

The markdown language should be sufficient for most tasks to draft a report, and the integration with RStudio makes it a real pleasure to work with knitr.

Unfortunately a spell checker is currently missing for knitr files, but I wouldn’t be surprised if this will be added to a future version of RStudio.