Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Interactive reports in R with knitr and RStudio
My first examples with [***knitr***](
Let's include some simple R code:
That worked.
Let's include a plot:
```{r fig.width=4, fig.height=4}
df <- data.frame(x=1:10, y=1:10)
plot(y ~ x, data=df, pch=19, col="blue")
Now let's insert an interactive chart with [***googleVis***](
## load the googleVis package
## create the scatter chart
sc <- gvisScatterChart(data=df,
options=list(width=300, height=300,
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'}
## {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:
```{r results='asis'}
geo <- gvisGeoChart(CityPopularity, locationvar='City',
options=list(region='US', height=350,
colorAxis="{colors: ['orange','blue']}") )
print(geo, 'chart')
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:
```{r results='asis'}
M <- gvisMotionChart(Fruits, "Fruit", "Year",
options=list(width=550, height=450))
print(M, 'chart')
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment