Required libraries

if (!require("pacman")) install.packages("pacman")
pacman::p_load(googleVis, devtools, pryr)

Shiny & rCharts

rCharts example

rCharts is not on CRAN, so…

library(devtools)
install_github('rCharts', 'ramnathv', ref = 'dev')
## Warning: Username parameter is deprecated. Please use ramnathv/rCharts
## Skipping install for github remote, the SHA1 (8d3fe35b) has not changed since last install.
##   Use `force = TRUE` to force installation

This setup is required, mainly to import CSS files that sets up width/height for the plots. It imports CSS files and JavaScript libraries from online resources.

library(rCharts)
## utility function to add required assets such as CSS and JS libraries
add_lib_assets <- function(lib, cdn = F,css=NULL) {
    assets = get_assets(get_lib(lib), cdn = cdn)
    if(!is.null(css)){assets$css=c(assets$css,css)}
    styles <- lapply(assets$css, function(style) {
        sprintf("<link rel='stylesheet' href=%s>", style)
    })

    scripts <- lapply(assets$jshead, function(script) {
        sprintf("<script type='text/javascript' src=%s></script>", script)
    })
    cat(paste(c(styles, scripts), collapse = "\n"))
}

# get assets from online repositories 
add_lib_assets("NVD3",cdn=TRUE,css="http://rawgithub.com/ramnathv/rCharts/master/inst/libraries/nvd3/css/rNVD3.css") 
add_lib_assets("Polycharts",cdn=TRUE)

Static plot, hover over data samples for more details

names(iris) = gsub("\\.", "", names(iris))
r1<-rPlot(SepalLength ~ SepalWidth | Species, data = iris, color = 'Species', type = 'point')
r1$print("polyScatter")

Slightly dynamic, you can select different types (grouped, stacked) for display.

hair_eye_male <- subset(as.data.frame(HairEyeColor), Sex == "Male")
n1 <- nPlot(Freq ~ Hair, group = "Eye", data = hair_eye_male, type = "multiBarChart")
n1$print("nvd3mbar")

Google Vis Example

Initialization

library(googleVis)
op <- options(gvis.plot.tag='chart')

Static plot:

CityPopularity$Mean=mean(CityPopularity$Popularity)
CC <- gvisComboChart(CityPopularity, xvar='City',
          yvar=c('Mean', 'Popularity'),
          options=list(seriesType='bars',
                       width=450, height=300,
                       title='City Popularity',
                       series='{0: {type:\"line\"}}'))
plot(CC)

Some animation:

M <- gvisMotionChart(Fruits, 'Fruit', 'Year', options=list(width=600, heigth=400))
plot(M)
options(op)

You can see a number of other cool plots and customizations with library(googleViz); demo(googleViz)

Classes

Examples of a few classes

class(rnorm(100))
## [1] "numeric"
class(NA)
## [1] "logical"
class('foo')
## [1] "character"
x <- rnorm(100)
y <- x + rnorm(100)
fit <- lm(y ~ x)
class(fit)
## [1] "lm"

Which method is being called?

set.seed(2)
x <- rnorm(100)
class(x)
## [1] "numeric"
mean(x)
## [1] -0.03069816

The class of x is numeric, but there is no mean function for numeric objects. Se we call the default function for method mean.

getS3method('mean', 'default')
## function (x, trim = 0, na.rm = FALSE, ...) 
## {
##     if (!is.numeric(x) && !is.complex(x) && !is.logical(x)) {
##         warning("argument is not numeric or logical: returning NA")
##         return(NA_real_)
##     }
##     if (na.rm) 
##         x <- x[!is.na(x)]
##     if (!is.numeric(trim) || length(trim) != 1L) 
##         stop("'trim' must be numeric of length one")
##     n <- length(x)
##     if (trim > 0 && n) {
##         if (is.complex(x)) 
##             stop("trimmed means are not defined for complex data")
##         if (anyNA(x)) 
##             return(NA_real_)
##         if (trim >= 0.5) 
##             return(stats::median(x, na.rm = FALSE))
##         lo <- floor(n * trim) + 1
##         hi <- n + 1 - lo
##         x <- sort.int(x, partial = unique(c(lo, hi)))[lo:hi]
##     }
##     .Internal(mean(x))
## }
## <bytecode: 0x7fdf3b446ad0>
## <environment: namespace:base>

S4 classes: creating a Polygon class:

library(methods)
setClass('polygon', representation(x='numeric', y='numeric'))

Creating a plot method with setMethod:

setMethod('plot', 'polygon',
          function(x, y, ...) {
              plot(x@x, x@y, type='n', ...)
              xp <- c(x@x, x@x[1])
              yp <- c(x@y, x@y[1])
              lines(xp, yp)
              })
## Creating a generic function for 'plot' from package 'graphics' in the global environment
## [1] "plot"

And here it is:

showMethods('plot')
## Function: plot (package graphics)
## x="ANY"
## x="git_repository"
## x="polygon"

And to get the body of this S4 method:

getMethod('plot', 'polygon')
## Method Definition:
## 
## function (x, y, ...) 
## {
##     plot(x@x, x@y, type = "n", ...)
##     xp <- c(x@x, x@x[1])
##     yp <- c(x@y, x@y[1])
##     lines(xp, yp)
## }
## 
## Signatures:
##         x        
## target  "polygon"
## defined "polygon"

Finally, using polygon and plot:

p <- new('polygon', x=c(1,2,3,4), y=c(1,2,3,1))
plot(p)

How to find out if a method is generic?

sapply(c('mean', 'show', 'lm', 'colSums', 'dgamma', 'predict'), isGeneric)
##    mean    show      lm colSums  dgamma predict 
##   FALSE    TRUE   FALSE   FALSE   FALSE   FALSE
library(pryr)
c(mean=ftype(mean), show=ftype(show), lm=ftype(lm), colsums=ftype(colSums), dgamma=ftype(dgamma), predict=ftype(predict))
##      mean1      mean2      show1      show2         lm    colsums 
##       "s3"  "generic"       "s4"  "generic" "function" "internal" 
##     dgamma   predict1   predict2 
## "function"       "s3"  "generic"