# Writing S3 Methods #------------------- # plot() doesn't have specific methods for dealing with # logical or character vectors. methods(plot) z <- rnorm(25) < 0 # setup y <- as.character(!z) plot(z) # calls plot.default(), which converts z to numeric plot.default(z) # you wouldn't normally bypass plot(), but you can plot(y) # calls plot.default(), which returns an ERROR plot.default(y) # We define two new functions, and name them like other plot methods # Note I've included some error checking plot.logical <- function (x) { if (class(x)=="logical") { x <- factor(x) plot(x, ylab="Frequency") } else { print("x is not of class 'logical'") } } plot.character <- function (x) { if (class(x)=="character") { x <- factor(x) plot(x, ylab="Frequency") } else { print("x is not of class 'character'") } } # We can use these new functions directly # and test to see if they work as expected plot.logical(z) plot.logical(y) plot.logical(data.frame(z,y)) plot.logical(matrix(z, nrow=5)) plot.character(y) plot.character(z) # Now see what happens when we go back to the plot() function plot(z) plot(y) # And check the list of plot() methods methods(plot)