1margin <- function(x, ...) { 2 UseMethod("margin") 3} 4 5margin.randomForest <- function(x, ...) { 6 if (x$type == "regression") { 7 stop("margin not defined for regression Random Forests") 8 } 9 if( is.null(x$votes) ) { 10 stop("margin is only defined if votes are present") 11 } 12 margin(x$votes, x$y, ...) 13} 14 15margin.default <- function(x, observed, ...) { 16 if ( !is.factor(observed) ) { 17 stop(deparse(substitute(observed)), " is not a factor") 18 } 19 if (ncol(x) != nlevels(observed)) 20 stop("number of columns in x must equal the number of levels in observed") 21 if (! all(colnames(x) %in% levels(observed)) || 22 ! all(levels(observed) %in% colnames(x))) 23 stop("column names of x must match levels of observed") 24 ## If the votes are not in fractions, normalize them to fractions. 25 if ( any(x > 1) ) x <- sweep(x, 1, rowSums(x), "/") 26 position <- match(as.character(observed), colnames(x)) 27 margin <- numeric(length(observed)) 28 for (i in seq_along(observed)) { 29 margin[i] <- x[i, position[i]] - max(x[i, -position[i]]) 30 } 31 names(margin) <- observed 32 class(margin) <- "margin" 33 margin 34} 35 36plot.margin <- function(x, sort=TRUE, ...) { 37 if (sort) x <- sort(x) 38 nF <- factor(names(x)) 39 nlevs <- length(levels(nF)) 40 if ( requireNamespace("RColorBrewer", quietly=TRUE) && nlevs < 12) { 41 pal <- RColorBrewer::brewer.pal(nlevs,"Set1") 42 } else { 43 pal <- rainbow(nlevs) 44 } 45 plot.default(x, col=pal[as.numeric(nF)], pch=20, ... ) 46} 47 48