content
stringlengths
0
14.9M
filename
stringlengths
44
136
# added lwd arg, changed default point sizes distplot <- function(x, type = c("poisson", "binomial", "nbinomial"), size = NULL, lambda = NULL, legend = TRUE, xlim = NULL, ylim = NULL, conf_int = TRUE, conf_level = 0.95, main = NULL, xlab = "Number of occurrences", ylab = "Distribution metameter", gp = gpar(cex = 0.8), lwd=2, gp_conf_int = gpar(lty = 2), name = "distplot", newpage = TRUE, pop = TRUE, return_grob = FALSE, ...) { if(is.vector(x)) { x <- table(x) } if(is.table(x)) { if(length(dim(x)) > 1) stop ("x must be a 1-way table") freq <- as.vector(x) count <- as.numeric(names(x)) } else { if(!(!is.null(ncol(x)) && ncol(x) == 2)) stop("x must be a 2-column matrix or data.frame") freq <- as.vector(x[,1]) count <- as.vector(x[,2]) } myindex <- (1:length(freq))[freq > 0] mycount <- count[myindex] myfreq <- freq[myindex] switch(match.arg(type), "poisson" = { par.ml <- suppressWarnings(goodfit(x, type = type)$par$lambda) phi <- function(nk, k, N, size = NULL) ifelse(nk > 0, lgamma(k + 1) + log(nk/N), NA) y <- phi(myfreq, mycount, sum(freq)) if(!is.null(lambda)) y <- y + lambda - mycount * log(lambda) fm <- lm(y ~ mycount) par.estim <- exp(coef(fm)[2]) names(par.estim) <- "lambda" txt <- "exp(slope)" if(!is.null(lambda)) { par.estim <- par.estim * lambda txt <- paste(txt, "x lambda") } legend.text <- paste(txt, "=", round(par.estim, digits = 3)) if(is.null(main)) main <- "Poissoness plot" }, "binomial" = { if(is.null(size)) { size <- max(count) warning("size was not given, taken as maximum count") } par.ml <- suppressWarnings(goodfit(x, type = type, par = list(size = size))$par$prob) phi <- function(nk, k, N, size = NULL) log(nk) - log(N * choose(size, k)) y <- phi(myfreq, mycount, sum(freq), size = size) fm <- lm(y ~ mycount) par.estim <- exp(coef(fm)[2]) par.estim <- par.estim / (1 + par.estim) names(par.estim) <- "prob" legend.text <- paste("inv.logit(slope) =", round(par.estim, digits = 3)) if(is.null(main)) main <- "Binomialness plot" }, "nbinomial" = { if(is.null(size)) { par.ml <- suppressWarnings(goodfit(x, type = type)$par) size <- par.ml$size par.ml <- par.ml$prob }else{ xbar <- weighted.mean(mycount, myfreq) par.ml <- size / (size+xbar) } phi <- function(nk, k, N, size = NULL) log(nk) - log(N * choose(size + k - 1, k)) y <- phi(myfreq, mycount, sum(freq), size = size) fm <- lm(y ~ mycount) par.estim <- 1 - exp(coef(fm)[2]) names(par.estim) <- "prob" legend.text <- paste("1-exp(slope) =", round(par.estim, digits = 3)) if(is.null(main)) main <- "Negative binomialness plot" }) yhat <- ifelse(myfreq > 1.5, myfreq - 0.67, 1/exp(1)) yhat <- phi(yhat, mycount, sum(freq), size = size) if(!is.null(lambda)) yhat <- yhat + lambda - mycount * log(lambda) phat <- myfreq / sum(myfreq) ci.width <- qnorm(1-(1 - conf_level)/2) * sqrt(1-phat)/sqrt(myfreq - (0.25 * phat + 0.47)*sqrt(myfreq)) RVAL <- cbind(count, freq, NA, NA, NA, NA, NA) RVAL[myindex,3:7] <- cbind(y,yhat,ci.width, yhat-ci.width, yhat + ci.width) RVAL <- as.data.frame(RVAL) names(RVAL) <- c("Counts", "Freq", "Metameter", "CI.center", "CI.width", "CI.lower", "CI.upper") if(is.null(xlim)) xlim <- range(RVAL[,1]) if(is.null(ylim)) ylim <- range(RVAL[,c(3,6,7)], na.rm = TRUE) xlim <- xlim + c(-1, 1) * diff(xlim) * 0.04 ylim <- ylim + c(-1, 1) * diff(ylim) * 0.04 if(newpage) grid.newpage() pushViewport(plotViewport(xscale = xlim, yscale = ylim, default.units = "native", name = name)) grid.points(x = RVAL[,1], y = RVAL[,3], default.units = "native", gp = gp, ...) grid.lines(x = xlim, y = predict(fm, newdata = data.frame(mycount = xlim)), default.units = "native", gp = gpar(lwd=lwd, col = 2)) grid.rect(gp = gpar(fill = "transparent")) grid.xaxis() grid.yaxis() grid.text(xlab, y = unit(-3.5, "lines")) grid.text(ylab, x = unit(-3, "lines"), rot = 90) grid.text(main, y = unit(1, "npc") + unit(2, "lines"), gp = gpar(fontface = "bold")) if(conf_int) { grid.points(x = RVAL[,1], y = RVAL[,4], pch = 19, gp = gpar(cex = 0.5)) grid.segments(RVAL[,1], RVAL[,6], RVAL[,1], RVAL[,7], default.units = "native", gp = gp_conf_int) } if(legend) { mymin <- which.min(RVAL[,5]) leg.x <- RVAL[mymin,1] if(RVAL[mymin,6] - ylim[1] > ylim[2] - RVAL[mymin,7]) leg.y <- ylim[1] + 0.7 * (RVAL[mymin,6] - ylim[1]) else leg.y <- ylim[2] legend.text <- c(paste("slope =", round(coef(fm)[2], digits = 3)), paste("intercept =", round(coef(fm)[1], digits = 3)), "", paste(names(par.estim),": ML =", round(par.ml, digits=3)), legend.text) legend.text <- paste(legend.text, collapse = "\n") grid.text(legend.text, leg.x, leg.y - 0.05 * abs(leg.y), default.units = "native", just = c("left", "top")) } if(pop) popViewport() else upViewport() if (return_grob) structure(invisible(RVAL), grob = grid.grab()) else invisible(RVAL) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/distplot.R
####################################### ### doubledecker plot doubledecker <- function(x, ...) UseMethod("doubledecker") doubledecker.formula <- function(formula, data = NULL, ..., main = NULL) { if (is.logical(main) && main) main <- deparse(substitute(data)) if (is.structable(data)) data <- as.table(data) m <- match.call(expand.dots = FALSE) edata <- eval(m$data, parent.frame()) fstr <- strsplit(paste(deparse(formula), collapse = ""), "~") vars <- strsplit(strsplit(gsub(" ", "", fstr[[1]][2]), "\\|")[[1]], "\\+") dep <- gsub(" ", "", fstr[[1]][1]) varnames <- vars[[1]] if (dep == "") stop("Need a dependent variable!") varnames <- c(varnames, dep) if(inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) { dat <- as.table(data) if(all(varnames != ".")) { ind <- match(varnames, names(dimnames(dat))) if (any(is.na(ind))) stop(paste("Can't find", paste(varnames[is.na(ind)], collapse=" / "), "in", deparse(substitute(data)))) dat <- margin.table(dat, ind) } else { ind <- match(dep, names(dimnames(dat))) if (is.na(ind)) stop(paste("Can't find", dep, "in", deparse(substitute(data)))) dat <- aperm(dat, c(seq_along(dim(dat))[-ind], ind)) } doubledecker.default(dat, main = main, ...) } else { tab <- if ("Freq" %in% colnames(data)) xtabs(formula(paste("Freq~", varnames, collapse = "+")), data = data) else xtabs(formula(paste("~", varnames, collapse = "+")), data = data) doubledecker.default(tab, main = main, ...) } } doubledecker.default <- function(x, depvar = length(dim(x)), margins = c(1, 4, length(dim(x)) + 1, 1), gp = gpar(fill = rev(gray.colors(tail(dim(x), 1)))), labeling = labeling_doubledecker, spacing = spacing_highlighting, main = NULL, keep_aspect_ratio = FALSE, ...) { x <- as.table(x) d <- dim(x) l <- length(d) if (is.character(depvar)) depvar <- match(depvar, names(dimnames(x))) condvars <- (1:l)[-depvar] ## order dependend var *last* x <- aperm(x, c(condvars, depvar)) ## recycle gpar elements along *last* dimension, if needed size <- prod(d) FUN <- function(par) { if (is.structable(par)) par <- as.table(par) if (length(par) < size || is.null(dim(par))) aperm(array(par, dim = rev(d))) else par } gp <- structure(lapply(gp, FUN), class = "gpar") strucplot(x, core = struc_mosaic(zero_split = FALSE, zero_shade = FALSE), condvars = l - 1, spacing = spacing, split_vertical = c(rep.int(TRUE, l - 1), FALSE), gp = gp, shade = TRUE, labeling = labeling, main = main, margins = margins, legend = NULL, keep_aspect_ratio = keep_aspect_ratio, ... ) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/doubledeckerplot.R
## Modifications - MF - 1 Dec 2010 # -- change default colors to more distinguishable values # -- allow to work with >3 dimensional arrays # -- modified defaults for mfrow/mfcol to give landscape display, nr <= nc, rather than nr >= nc # Take a 2+D array and return a 3D array, with dimensions 3+ as a single dimension # Include as a separate function, since it is useful in other contexts array3d <- function(x, sep=':') { if(length(dim(x)) == 2) { x <- if(is.null(dimnames(x))) array(x, c(dim(x), 1)) else array(x, c(dim(x), 1), c(dimnames(x), list(NULL))) return(x) } else if(length(dim(x))==3) return(x) else { x3d <- array(x, c(dim(x)[1:2], prod(dim(x)[-(1:2)]))) if (!is.null(dimnames(x))) { n3d <- paste(names(dimnames(x))[-(1:2)], collapse=sep) d3d <- apply(expand.grid(dimnames(x)[-(1:2)]), 1, paste, collapse=sep) dimnames(x3d) <- c(dimnames(x)[1:2], list(d3d)) names(dimnames(x3d))[3] <- n3d } return(x3d) } } "fourfold" <- function(x, # color = c("#99CCFF","#6699CC","#FF5050","#6060A0", "#FF0000", "#000080"), color = c("#99CCFF","#6699CC","#FFA0A0","#A0A0FF", "#FF0000", "#000080"), conf_level = 0.95, std = c("margins", "ind.max", "all.max"), margin = c(1, 2), space = 0.2, main = NULL, sub = NULL, mfrow = NULL, mfcol = NULL, extended = TRUE, ticks = 0.15, p_adjust_method = p.adjust.methods, newpage = TRUE, fontsize = 12, default_prefix = c("Row", "Col", "Strata"), sep = ": ", varnames = TRUE, return_grob = FALSE) { ## Code for producing fourfold displays. ## Reference: ## Friendly, M. (1994). ## A fourfold display for 2 by 2 by \eqn{k} tables. ## Technical Report 217, York University, Psychology Department. ## http://datavis.ca/papers/4fold/4fold.pdf ## ## Implementation notes: ## ## We need plots with aspect ratio FIXED to 1 and glued together. ## Hence, even if k > 1 we prefer keeping everything in one plot ## region rather than using a multiple figure layout. ## Each 2 by 2 pie is is drawn into a square with x/y coordinates ## between -1 and 1, with row and column labels in [-1-space, -1] ## and [1, 1+space], respectively. If k > 1, strata labels are in ## an area with y coordinates in [1+space, 1+(1+gamma)*space], ## where currently gamma=1.25. The pies are arranged in an nr by ## nc layout, with horizontal and vertical distances between them ## set to space. ## ## The drawing code first computes the complete are of the form ## [0, totalWidth] x [0, totalHeight] ## needed and sets the world coordinates using plot.window(). ## Then, the strata are looped over, and the corresponding pies ## added by filling rows or columns of the layout as specified by ## the mfrow or mfcol arguments. The world coordinates are reset ## in each step by shifting the origin so that we can always plot ## as detailed above. if(!is.array(x)) stop("x must be an array") dimx <- dim(x) # save original dimensions for setting default mfrow/mfcol when length(dim(x))>3 x <- array3d(x) if(any(dim(x)[1:2] != 2)) stop("table for each stratum must be 2 by 2") dnx <- dimnames(x) if(is.null(dnx)) dnx <- vector("list", 3) for(i in which(sapply(dnx, is.null))) dnx[[i]] <- LETTERS[seq(length.out = dim(x)[i])] if(is.null(names(dnx))) i <- 1 : 3 else i <- which(is.null(names(dnx))) if(any(i > 0)) names(dnx)[i] <- default_prefix[i] dimnames(x) <- dnx k <- dim(x)[3] if(!((length(conf_level) == 1) && is.finite(conf_level) && (conf_level >= 0) && (conf_level < 1))) stop("conf_level must be a single number between 0 and 1") if(conf_level == 0) conf_level <- FALSE std <- match.arg(std) findTableWithOAM <- function(or, tab) { ## Find a 2x2 table with given odds ratio `or' and the margins ## of a given 2x2 table `tab'. m <- rowSums(tab)[1] n <- rowSums(tab)[2] t <- colSums(tab)[1] if(or == 1) x <- t * n / (m + n) else if(or == Inf) x <- max(0, t - m) else { A <- or - 1 B <- or * (m - t) + (n + t) C <- - t * n x <- (- B + sqrt(B ^ 2 - 4 * A * C)) / (2 * A) } matrix(c(t - x, x, m - t + x, n - x), nrow = 2) } drawPie <- function(r, from, to, n = 500, color = "transparent") { p <- 2 * pi * seq(from, to, length.out = n) / 360 x <- c(cos(p), 0) * r y <- c(sin(p), 0) * r grid.polygon(x, y, gp = gpar(fill = color), default.units = "native") invisible(NULL) } stdize <- function(tab, std, x) { ## Standardize the 2 x 2 table `tab'. if(std == "margins") { if(all(sort(margin) == c(1, 2))) { ## standardize to equal row and col margins u <- sqrt(odds(tab)$or) u <- u / (1 + u) y <- matrix(c(u, 1 - u, 1 - u, u), nrow = 2) } else if(margin %in% c(1, 2)) y <- prop.table(tab, margin) else stop("incorrect margin specification") } else if(std == "ind.max") y <- tab / max(tab) else if(std == "all.max") y <- tab / max(x) y } odds <- function(x) { ## Given a 2 x 2 or 2 x 2 x k table `x', return a list with ## components `or' and `se' giving the odds ratios and standard ## deviations of the log odds ratios. if(length(dim(x)) == 2) { dim(x) <- c(dim(x), 1) k <- 1 } else k <- dim(x)[3] or <- double(k) se <- double(k) for(i in 1 : k) { f <- x[ , , i] if(any(f == 0)) f <- f + 0.5 or[i] <- (f[1, 1] * f[2, 2]) / (f[1, 2] * f[2, 1]) se[i] <- sqrt(sum(1 / f)) } list(or = or, se = se) } gamma <- 1.25 # Scale factor for strata labels angle.f <- c( 90, 180, 0, 270) # `f' for `from' angle.t <- c(180, 270, 90, 360) # `t' for `to' byrow <- FALSE if(!is.null(mfrow)) { nr <- mfrow[1] nc <- mfrow[2] } else if(!is.null(mfcol)) { nr <- mfcol[1] nc <- mfcol[2] byrow <- TRUE } else if(length(dimx)>3) { nr <- dimx[3] nc <- prod(dimx[-(1:3)]) } else { # nr <- ceiling(sqrt(k)) nr <- round(sqrt(k)) nc <- ceiling(k / nr) } if(nr * nc < k) stop("incorrect geometry specification") if(byrow) indexMatrix <- expand.grid(1 : nc, 1 : nr)[, c(2, 1)] else indexMatrix <- expand.grid(1 : nr, 1 : nc) totalWidth <- nc * 2 * (1 + space) + (nc - 1) * space totalHeight <- if(k == 1) 2 * (1 + space) else nr * (2 + (2 + gamma) * space) + (nr - 1) * space xlim <- c(0, totalWidth) ylim <- c(0, totalHeight) if (newpage) grid.newpage() if (!is.null(main) || !is.null(sub)) pushViewport(viewport(height = 1 - 0.1 * sum(!is.null(main), !is.null(sub)), width = 0.9, y = 0.5 - 0.05 * sum(!is.null(main), - !is.null(sub)) ) ) pushViewport(viewport(xscale = xlim, yscale = ylim, width = unit(min(totalWidth / totalHeight, 1), "snpc"), height = unit(min(totalHeight / totalWidth, 1), "snpc"))) o <- odds(x) ## perform logoddsratio-test for each stratum (H0: lor = 0) and adjust p-values if(is.numeric(conf_level) && extended) p.lor.test <- p.adjust(sapply(1 : k, function(i) { u <- abs(log(o$or[i])) / o$se[i] 2 * (1 - pnorm(u)) }), method = p_adjust_method ) scale <- space / (2 * convertY(unit(1, "strheight", "Ag"), "native", valueOnly = TRUE) ) v <- 0.95 - max(convertX(unit(1, "strwidth", as.character(c(x))), "native", valueOnly = TRUE) ) / 2 fontsize = fontsize * scale for(i in 1 : k) { tab <- x[ , , i] fit <- stdize(tab, std, x) xInd <- indexMatrix[i, 2] xOrig <- 2 * xInd - 1 + (3 * xInd - 2) * space yInd <- indexMatrix[i, 1] yOrig <- if(k == 1) (1 + space) else (totalHeight - (2 * yInd - 1 + ((3 + gamma) * yInd - 2) * space)) pushViewport(viewport(xscale = xlim - xOrig, yscale = ylim - yOrig)) ## drawLabels() u <- 1 + space / 2 adjCorr <- 0.2 grid.text( paste(names(dimnames(x))[1], dimnames(x)[[1]][1], sep = sep), 0, u, gp = gpar(fontsize = fontsize), default.units = "native" ) grid.text( paste(names(dimnames(x))[2], dimnames(x)[[2]][1], sep = sep), -u, 0, default.units = "native", gp = gpar(fontsize = fontsize), rot = 90) grid.text( paste(names(dimnames(x))[1], dimnames(x)[[1]][2], sep = sep), 0, -u, gp = gpar(fontsize = fontsize), default.units = "native" ) grid.text( paste(names(dimnames(x))[2], dimnames(x)[[2]][2], sep = sep), u, 0, default.units = "native", gp = gpar(fontsize = fontsize), rot = 90) if (k > 1) { grid.text(if (!varnames) dimnames(x)[[3]][i] else paste(names(dimnames(x))[3], dimnames(x)[[3]][i], sep = sep), 0, 1 + (1 + gamma / 2) * space, gp = gpar(fontsize = fontsize * gamma), default.units = "native" ) } ## drawFrequencies() ### in extended plots, emphasize charts with significant logoddsratios emphasize <- if(extended && is.numeric(conf_level)) 2 * extended * (1 + (p.lor.test[i] < 1 - conf_level)) else 0 d <- odds(tab)$or drawPie(sqrt(fit[1,1]), 90, 180, color = color[1 + (d > 1) + emphasize]) drawPie(sqrt(fit[2,1]), 180, 270, color = color[2 - (d > 1) + emphasize]) drawPie(sqrt(fit[1,2]), 0, 90, color = color[2 - (d > 1) + emphasize]) drawPie(sqrt(fit[2,2]), 270, 360, color = color[1 + (d > 1) + emphasize]) u <- 1 - space / 2 grid.text(as.character(c(tab))[1], -v, u, just = c("left", "top"), gp = gpar(fontsize = fontsize), default.units = "native") grid.text(as.character(c(tab))[2], -v, -u, just = c("left", "bottom"), gp = gpar(fontsize = fontsize), default.units = "native") grid.text(as.character(c(tab))[3], v, u, just = c("right", "top"), gp = gpar(fontsize = fontsize), default.units = "native") grid.text(as.character(c(tab))[4], v, -u, just = c("right", "bottom"), gp = gpar(fontsize = fontsize), default.units = "native") ## draw ticks if(extended && ticks) if(d > 1) { grid.lines(c(sqrt(fit[1,1]) * cos(3*pi/4), (sqrt(fit[1,1]) + ticks) * cos(3*pi/4)), c(sqrt(fit[1,1]) * sin(3*pi/4), (sqrt(fit[1,1]) + ticks) * sin(3*pi/4)), gp = gpar(lwd = 1), default.units = "native" ) grid.lines(c(sqrt(fit[2,2]) * cos(-pi/4), (sqrt(fit[2,2]) + ticks) * cos(-pi/4)), c(sqrt(fit[2,2]) * sin(-pi/4), (sqrt(fit[2,2]) + ticks) * sin(-pi/4)), gp = gpar(lwd = 1), default.units = "native" ) } else { grid.lines(c(sqrt(fit[1,2]) * cos(pi/4), (sqrt(fit[1,2]) + ticks) * cos(pi/4)), c(sqrt(fit[1,2]) * sin(pi/4), (sqrt(fit[1,2]) + ticks) * sin(pi/4)), gp = gpar(lwd = 1), default.units = "native" ) grid.lines(c(sqrt(fit[2,1]) * cos(-3*pi/4), (sqrt(fit[2,1]) + ticks) * cos(-3*pi/4)), c(sqrt(fit[2,1]) * sin(-3*pi/4), (sqrt(fit[2,1]) + ticks) * sin(-3*pi/4)), gp = gpar(lwd = 1), default.units = "native" ) } ## drawConfBands() if(is.numeric(conf_level)) { or <- o$or[i] se <- o$se[i] ## lower theta <- or * exp(qnorm((1 - conf_level) / 2) * se) tau <- findTableWithOAM(theta, tab) r <- sqrt(c(stdize(tau, std, x))) for(j in 1 : 4) drawPie(r[j], angle.f[j], angle.t[j]) ## upper theta <- or * exp(qnorm((1 + conf_level) / 2) * se) tau <- findTableWithOAM(theta, tab) r <- sqrt(c(stdize(tau, std, x))) for(j in 1 : 4) drawPie(r[j], angle.f[j], angle.t[j]) } ## drawBoxes() grid.polygon(c(-1, 1, 1, -1), c(-1, -1, 1, 1), default.units = "native", gp = gpar(fill = "transparent") ) grid.lines(c(-1, 1), c(0, 0), default.units = "native") for(j in seq(from = -0.8, to = 0.8, by = 0.2)) grid.lines(c(j, j), c(-0.02, 0.02), default.units = "native") for(j in seq(from = -0.9, to = 0.9, by = 0.2)) grid.lines(c(j, j), c(-0.01, 0.01), default.units = "native") grid.lines(c(0, 0), c(-1, 1), default.units = "native") for(j in seq(from = -0.8, to = 0.8, by = 0.2)) grid.lines(c(-0.02, 0.02), c(j, j), default.units = "native") for(j in seq(from = -0.9, to = 0.9, by = 0.2)) grid.lines(c(-0.01, 0.01), c(j, j), default.units = "native") popViewport(1) } if(!is.null(main) || !is.null(sub)) { if (!is.null(main)) grid.text(main, y = unit(1, "npc") + unit(1, "lines"), gp = gpar(fontsize = 20, fontface = 2)) if (!is.null(sub)) grid.text(sub, y = unit(0, "npc") - unit(1, "lines"), gp = gpar(fontsize = 20, fontface = 2)) popViewport(1) } popViewport(1) if (return_grob) return(invisible(grid.grab())) else return(invisible(NULL)) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/fourfold.R
goodfit <- function(x, type = c("poisson", "binomial", "nbinomial"), method = c("ML", "MinChisq"), par = NULL) { if(is.vector(x)) { x <- table(x) } if(is.table(x)) { if(length(dim(x)) > 1) stop ("x must be a 1-way table") freq <- as.vector(x) count <- as.numeric(names(x)) } else { if(!(!is.null(ncol(x)) && ncol(x) == 2)) stop("x must be a 2-column matrix or data.frame") freq <- as.vector(x[,1]) count <- as.vector(x[,2]) } ## fill-in possibly missing cells nfreq <- rep(0, max(count) + 1) nfreq[count + 1] <- freq freq <- nfreq count <- 0:max(count) n <- length(count) ## starting value for degrees of freedom df <- -1 type <- match.arg(type) method <- match.arg(method) switch(type, "poisson" = { if(!is.null(par)) { if(!is.list(par)) stop("`par' must be a named list") if(names(par) != "lambda") stop("`par' must specify `lambda'") par <- par$lambda method <- "fixed" } else if(method == "ML") { df <- df - 1 par <- weighted.mean(count,freq) } else if(method == "MinChisq") { df <- df - 1 chi2 <- function(x) { p.hat <- diff(c(0, ppois(count[-n], lambda = x), 1)) expected <- sum(freq) * p.hat sum((freq - expected)^2/expected) } par <- optimize(chi2, range(count))$minimum } par <- list(lambda = par) p.hat <- dpois(count, lambda = par$lambda) }, "binomial" = { size <- par$size if(is.null(size)) { size <- max(count) warning("size was not given, taken as maximum count") } if(size > max(count)) { nfreq <- rep(0, size + 1) nfreq[count + 1] <- freq freq <- nfreq count <- 0:size n <- length(count) } if(!is.null(par$prob)) { if(!is.list(par)) stop("`par' must be a named list and specify `prob'") par <- par$prob method <- "fixed" } else if(method == "ML") { df <- df - 1 par <- weighted.mean(count/size, freq) } else if(method == "MinChisq") { df <- df - 1 chi2 <- function(x) { p.hat <- diff(c(0, pbinom(count[-n], prob = x, size = size), 1)) expected <- sum(freq) * p.hat sum((freq - expected)^2/expected) } par <- optimize(chi2, c(0,1))$minimum } par <- list(prob = par, size = size) p.hat <- dbinom(count, prob = par$prob, size = par$size) }, "nbinomial" = { if(!is.null(par)) { if(!is.list(par)) stop("`par' must be a named list") if(!(isTRUE(all.equal(names(par), "size")) | isTRUE(all.equal(sort(names(par)), c("prob", "size"))))) stop("`par' must specify `size' and possibly `prob'") if(!is.null(par$prob)) method <- "fixed" } switch(method, "ML" = { if(is.null(par$size)) { df <- df - 2 par <- fitdistr(rep(count, freq), "negative binomial")$estimate par <- par[1]/c(1, sum(par)) } else { df <- df - 1 method <- c("ML", "with size fixed") size <- par$size xbar <- weighted.mean(count,freq) par <- c(size, size/(xbar+size)) } }, "MinChisq" = { if(is.null(par$size)) { df <- df - 2 ## MM xbar <- weighted.mean(count,freq) s2 <- var(rep(count,freq)) p <- xbar / s2 size <- xbar^2/(s2 - xbar) par1 <- c(size, p) ## minChisq chi2 <- function(x) { p.hat <- diff(c(0, pnbinom(count[-n], size = x[1], prob = x[2]), 1)) expected <- sum(freq) * p.hat sum((freq - expected)^2/expected) } par <- optim(par1, chi2)$par } else { df <- df - 1 method <- c("MinChisq", "with size fixed") chi2 <- function(x) { p.hat <- diff(c(0, pnbinom(count[-n], size = par$size, prob = x), 1)) expected <- sum(freq) * p.hat sum((freq - expected)^2/expected) } par <- c(par$size, optimize(chi2, c(0, 1))$minimum) } }, "fixed" = { par <- c(par$size, par$prob) }) par <- list(size = par[1], prob = par[2]) p.hat <- dnbinom(count, size = par$size, prob = par$prob) }) expected <- sum(freq) * p.hat df <- switch(method[1], "MinChisq" = { length(freq) + df }, "ML" = { sum(freq > 0) + df }, "fixed" = { c(length(freq), sum(freq > 0)) + df } ) structure(list(observed = freq, count = count, fitted = expected, type = type, method = method, df = df, par = par), class = "goodfit") } # does this need a residuals_type arg? print.goodfit <- function(x, residuals_type = c("pearson", "deviance", "raw"), ...) { residuals_type <- match.arg(residuals_type) cat(paste("\nObserved and fitted values for", x$type, "distribution\n")) if(x$method[1] == "fixed") cat("with fixed parameters \n\n") else cat(paste("with parameters estimated by `", paste(x$method, collapse = " "), "' \n\n", sep = "")) resids <- residuals(x, type = residuals_type) RVAL <- cbind(x$count, x$observed, x$fitted, resids) colnames(RVAL) <- c("count", "observed", "fitted", paste(residuals_type, "residual")) rownames(RVAL) <- rep("", nrow(RVAL)) print(RVAL, ...) invisible(x) } summary.goodfit <- function(object, ...) { df <- object$df obsrvd <- object$observed count <- object$count expctd <- fitted(object) G2 <- sum(ifelse(obsrvd == 0, 0, obsrvd * log(obsrvd/expctd))) * 2 n <- length(obsrvd) pfun <- switch(object$type, poisson = "ppois", binomial = "pbinom", nbinomial = "pnbinom") p.hat <- diff(c(0, do.call(pfun, c(list(q = count[-n]), object$par)), 1)) expctd <- p.hat * sum(obsrvd) X2 <- sum((obsrvd - expctd)^2 / expctd) names(G2) <- "Likelihood Ratio" names(X2) <- "Pearson" if(any(expctd < 5) & object$method[1] != "ML") warning("Chi-squared approximation may be incorrect") RVAL <- switch(object$method[1], ML = G2, MinChisq = X2, fixed = c(X2, G2) ) RVAL <- cbind(RVAL, df, pchisq(RVAL, df = df, lower.tail = FALSE)) colnames(RVAL) <- c("X^2", "df", "P(> X^2)") cat(paste("\n\t Goodness-of-fit test for", object$type, "distribution\n\n")) print(RVAL, ...) invisible(RVAL) } plot.goodfit <- function(x, ...) { rootogram(x, ...) } fitted.goodfit <- function(object, ...) { object$fitted } residuals.goodfit <- function(object, type = c("pearson", "deviance", "raw"), ...) { obsrvd <- object$observed expctd <- fitted(object) count <- object$count n <- length(obsrvd) pfun <- switch(object$type, poisson = "ppois", binomial = "pbinom", nbinomial = "pnbinom") p.hat <- diff(c(0, do.call(pfun, c(list(q = count[-n]), object$par)), 1)) expctd <- p.hat * sum(obsrvd) res <- switch(match.arg(type), pearson = (obsrvd - expctd) / sqrt(expctd), deviance = ifelse(obsrvd == 0, 0, obsrvd * log(obsrvd / expctd)), obsrvd - expctd) return(res) } predict.goodfit <- function(object, newcount = NULL, type = c("response", "prob"), ...) { if(is.null(newcount)) newcount <- object$count type <- match.arg(type) densfun <- switch(object$type, poisson = "dpois", binomial = "dbinom", nbinomial = "dnbinom") RVAL <- do.call(densfun, c(list(x = newcount), object$par)) if (type == "response") RVAL <- RVAL * sum(object$observed) return(RVAL) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/goodfit.R
grid_legend <- function (x, y, pch = NA, col = par('col'), labels, frame = TRUE, hgap = unit(0.8, "lines"), vgap = unit(0.8, "lines"), default_units = "lines", gp = gpar(), draw = TRUE, title = NULL, just = 'center', lwd = NA, lty = NA, size = 1, gp_title = NULL, gp_labels = NULL, gp_frame = gpar(fill = "transparent"), inset = c(0, 0)) { inset <- rep(inset, length.out = 2) if((length(x) > 1) && missing(y)) { y <- x[2] x <- x[1] } if(is.character(x)) switch(x, left = {x = unit(0 + inset[1],'npc'); y = unit(0.5 + inset[2],'npc'); just = c("left","center")}, topleft = {x = unit(0 + inset[1],'npc'); y = unit(1 - inset[2],'npc'); just = c(0,1)}, top = {x = unit(0.5 + inset[1],'npc'); y = unit(1 - inset[2],'npc'); just = c("center", "top")}, topright = {x = unit(1 - inset[1],'npc'); y = unit(1 - inset[2],'npc'); just = c(1,1)}, center = {x = unit(0.5 + inset[1],'npc'); y = unit(0.5 + inset[2],'npc'); just = c("center","center")}, bottom = {x = unit(0.5 - inset[1],'npc'); y = unit(0 + inset[2],'npc'); just = c("center","bottom")}, bottomright = {x = unit(1 - inset[1],'npc'); y = unit(0 + inset[2],'npc'); just = c(1,0)}, right = {x = unit(1 - inset[1],'npc'); y = unit(0.5 + inset[2],'npc'); just = c("right","center")}, bottomleft = {x = unit(0 + inset[1],'npc'); y = unit(0 + inset[2],'npc'); just = c(0,0)}) labels <- as.character(labels) nlabs <- length(labels) if(length(pch) == 1) pch <- rep(pch, nlabs) if(length(lwd) == 1) lwd <- rep(lwd, nlabs) if(length(lty) == 1) lty <- rep(lty, nlabs) if(length(col) == 1) col <- rep(col, nlabs) if(length(gp_labels) == 1) gp_labels <- rep(list(gp_labels), nlabs) if (is.logical(title) && !title) title <- NULL if(is.null(title)) tit <- 0 else tit <- 1 if (!is.unit(hgap)) hgap <- unit(hgap, default_units) if (length(hgap) != 1) stop("hgap must be single unit") if (!is.unit(vgap)) vgap <- unit(vgap, default_units) if (length(vgap) != 1) stop("vgap must be single unit") if(tit) legend.layout <- grid.layout(nlabs + tit, 3, widths = unit.c(unit(2, "lines"), max(unit(rep(1, nlabs), "strwidth", as.list(c(labels))), unit(1, "strwidth", title) - unit(2, "lines")), hgap), heights = unit.pmax(unit(1, "lines"), vgap + unit(rep(1, nlabs + tit ), "strheight", as.list(c(labels,title))))) else legend.layout <- grid.layout(nlabs, 3, widths = unit.c(unit(2, "lines"), max(unit(rep(1, nlabs), "strwidth", as.list(labels))), hgap), heights = unit.pmax(unit(1, "lines"), vgap + unit(rep(1, nlabs), "strheight", as.list(labels)))) fg <- frameGrob(layout = legend.layout, gp = gp) if (frame) fg <- placeGrob(fg, rectGrob(gp = gp_frame)) if (tit) fg <- placeGrob(fg, textGrob(title, x = .2, y = 0.5, just = c("left", "center"), gp = gp_title), col = 1, row = 1) for (i in 1:nlabs) { if(!is.na(pch[i])) fg <- placeGrob(fg, pointsGrob(0.5, 0.5, pch = pch[i], size = unit(size, "char"), gp = gpar(col = col[i])), col = 1, row = i + tit) else if(!is.na(lwd[i]) || !is.na(lty[i])) fg <- placeGrob(fg, linesGrob( unit(c(0.2, .8), "npc"), unit(c(.5), "npc"), gp = gpar(col = col[i], lwd = lwd[i], lty=lty[i])), col = 1, row = i + tit) fg <- placeGrob(fg, textGrob(labels[i], x = .1, y = 0.5, just = c("left", "center"), gp = gp_labels[[i]]), col = 2, row = i + tit) } pushViewport(viewport(x, y, height = grobHeight(fg), width = grobWidth(fg), just = just )) if (draw) grid.draw(fg) popViewport(1) invisible(fg) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/grid_legend.R
hls <- function(h = 1, l = 0.5, s = 1) { RGB <- function(q1, q2, hue) { if (hue > 360) hue <- hue - 360 if (hue < 0) hue <- hue + 360 if (hue < 60) q1 + (q2 - q1) * hue / 60 else if (hue < 180) q2 else if (hue < 240) q1 + (q2 - q1) * (240 - hue) / 60 else q1 } h <- h * 360 p2 <- if (l <= 0.5) l * (1 + s) else l + s - (l * s) p1 <- 2 * l - p2; if (s == 0) R <- G <- B <- l else { R <- RGB(p1, p2, h + 120) G <- RGB(p1, p2, h) B <- RGB(p1, p2, h - 120) } rgb(R, G, B) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/hls.R
################################################################ ## labeling pexpand <- function(par, len, default_value, default_names, choices = NULL) { if (is.null(par)) par <- default_value nam <- names(par) if (!is.null(choices)) par <- sapply(par, match.arg, choices) if (is.null(nam)) { default_value <- par par <- rep(par, length.out = len) nam <- names(par) <- default_names } else if (length(nam[nam == ""])) { default_value <- par[nam == ""] nam <- nam[nam != ""] } ret <- rep(default_value, length.out = len) if (!is.null(nam)) { names(ret) <- default_names ret[nam] <- par[nam] } ret } labeling_list <- function(gp_text = gpar(), just = "left", pos = "left", lsep = ": ", sep = " ", offset = unit(c(2, 2), "lines"), varnames = TRUE, cols = 2, ...) { function(d, split_vertical, condvars, prefix = "") { if (is.table(d) || is.structable(d)) d <- dimnames(d) ld <- length(d) labeling_border(labels = FALSE, varnames = varnames)(d, split_vertical, condvars, prefix) seekViewport(paste(prefix, "margin_bottom", sep = "")) pos <- unit(switch(pos, left = 0, center = 0.5, 1) / cols, "npc") ind <- split(seq(ld), rep.int(seq(cols), ceiling(ld / cols))[seq(ld)]) for (i in seq_along(ind)) grid.text(x = offset[1] + pos + unit((i - 1) / cols, "npc"), y = unit(1, "npc") - offset[2], paste(names(d[ind[[i]]]), sapply(d[ind[[i]]], paste, collapse = sep), sep = lsep, collapse = "\n" ), just = c(just, "top"), gp = gp_text ) } } class(labeling_list) <- "grapcon_generator" labeling_conditional <- function(...) { function (d, split_vertical, condvars, prefix = "") { if (is.table(d) || is.structable(d)) d <- dimnames(d) v <- rep.int(TRUE, length(d)) v[seq(condvars)] <- FALSE labeling_border(labels = !v, ...)(d, split_vertical, condvars, prefix) labeling_cells(labels = v, ...)(d, split_vertical, condvars, prefix) } } class(labeling_conditional) <- "grapcon_generator" labeling_cells <- function(labels = TRUE, varnames = TRUE, abbreviate_labels = FALSE, abbreviate_varnames = FALSE, gp_text = gpar(), lsep = ": ", lcollapse = "\n", just = "center", pos = "center", rot = 0, margin = unit(0.5, "lines"), clip_cells = TRUE, text = NULL, ...) { function(d, split_vertical, condvars, prefix = "") { if (is.table(d) || is.structable(d)) d <- dimnames(d) dn <- names(d) ld <- length(d) ## expand parameters if (length(pos) < 2) pos <- c(pos, pos) labels <- pexpand(labels, ld, TRUE, dn) varnames <- pexpand(varnames, ld, TRUE, dn) abbreviate_labels <- pexpand(abbreviate_labels, ld, FALSE, dn) abbreviate_varnames <- pexpand(abbreviate_varnames, ld, FALSE, dn) ## margin if (!is.unit(margin)) margin <- unit(margin, "lines") prvars <- ifelse(abbreviate_varnames, sapply(seq_along(dn), function(i) abbreviate(dn[i], abbreviate_varnames[i])), dn) prvars <- ifelse(varnames, paste(prvars, lsep, sep = ""), "") if (is.structable(text)) text <- as.table(text) ## draw labels split <- function(vind = 1, labs = c()) { n <- d[[vind]] for (labind in seq_along(n)) { lab <- c(labs, n[labind]) names(lab) <- names(d)[1:vind] mlab <- paste(prefix, "cell:", paste(dn[1:vind], lab, sep = "=", collapse = ","), sep = "") if (vind < ld) split(vind + 1, lab) else { seekViewport(mlab) pushViewport(viewport(width = max(unit(0, "npc"), unit(1, "npc") - 2 * margin), height = unit(1, "npc") - 2 * margin, clip = clip_cells)) txt <- if (!is.null(text)) { lab <- lab[names(dimnames(text))] do.call("[", c(list(text), as.list(lab))) } else { prlab <- ifelse(abbreviate_labels, sapply(seq_along(lab), function(i) abbreviate(lab[i], abbreviate_labels[i])), lab) prlab <- prlab[labels[1:ld]] paste(prvars[labels[1:ld]], prlab, sep = "", collapse = lcollapse) } grid.text(if(!is.na(txt)) txt, x = switch(pos[1], left =, top = 0, center = 0.5, 1), y = switch(pos[2], left =, top = 1, center = 0.5, 0), gp = gp_text, just = just, rot = rot) popViewport() } } } split() seekViewport(paste(prefix, "base", sep = "")) upViewport(1) } } class(labeling_cells) <- "grapcon_generator" labeling_border <- function(labels = TRUE, varnames = labels, set_labels = NULL, set_varnames = NULL, tl_labels = NULL, alternate_labels = FALSE, tl_varnames = NULL, gp_labels = gpar(fontsize = 12), gp_varnames = gpar(fontsize = 12, fontface = 2), rot_labels = c(0, 90, 0, 90), rot_varnames = c(0, 90, 0, 90), pos_labels = "center", pos_varnames = "center", just_labels = "center", just_varnames = pos_varnames, boxes = FALSE, fill_boxes = FALSE, offset_labels = c(0, 0, 0, 0), offset_varnames = offset_labels, labbl_varnames = NULL, labels_varnames = FALSE, sep = ": ", abbreviate_labs = FALSE, rep = TRUE, clip = FALSE, ... ) { ## expand parameters that apply to the four table margins pos_labels <- pexpand(pos_labels, 4, "center", c("top", "right", "bottom", "left"), c("left", "center", "right")) just_labels <- pexpand(just_labels, 4, "center", c("top", "right", "bottom", "left"), c("left", "center", "right")) offset_varnames <- if (!is.unit(offset_varnames)) unit(pexpand(offset_varnames, 4, rep.int(0, 4), c("top","right","bottom","left")), "lines") else rep(offset_varnames, length.out = 4) offset_labels <- if (!is.unit(offset_labels)) unit(pexpand(offset_labels, 4, rep.int(0, 4), c("top","right","bottom","left")), "lines") else rep(offset_labels, length.out = 4) rot_labels <- pexpand(rot_labels, 4, c(0, 90, 0, 90), c("top", "right", "bottom", "left")) if (inherits(gp_varnames, "gpar")) gp_varnames <- list(gp_varnames) gp_varnames <- pexpand(gp_varnames, 4, list(gpar(fontsize = 12, fontface = 2)), c("top", "right", "bottom", "left")) rot_varnames <- pexpand(rot_varnames, 4, c(0, 90, 0, 90), c("top", "right", "bottom", "left")) pos_varnames <- pexpand(pos_varnames, 4, "center", c("top", "right", "bottom", "left"), c("left", "center", "right")) just_varnames <- pexpand(just_varnames, 4, pos_varnames, c("top", "right", "bottom", "left"), c("left", "center", "right")) function(d, split_vertical, condvars, prefix = "") { if (is.table(d) || is.structable(d)) d <- dimnames(d) dn <- names(d) ld <- length(d) ## expand table- (i.e., dimensionality)-dependent parameters clip <- pexpand(clip, ld, TRUE, dn) labels <- pexpand(labels, ld, TRUE, dn) labels_varnames <- pexpand(labels_varnames, ld, FALSE, dn) ## tl_labels def <- logical() def[split_vertical] <- rep(c(TRUE, FALSE), length.out = sum(split_vertical)) def[!split_vertical] <- rep(c(TRUE, FALSE), length.out = sum(!split_vertical)) tl_labels <- if (is.null(tl_labels)) def else pexpand(tl_labels, ld, def, dn) ## rep labels rep <- pexpand(rep, ld, TRUE, dn) printed <- lapply(d, function(i) rep.int(FALSE, length(i))) ## alternate labels alternate_labels <- pexpand(alternate_labels, ld, FALSE, dn) ## abbreviate abbreviate_labs <- pexpand(abbreviate_labs, ld, FALSE, dn) labs <- d for (i in seq_along(d)) if (abbreviate_labs[i]) labs[[i]] <- abbreviate(labs[[i]], abbreviate_labs[i]) ## gp_labels if (inherits(gp_labels, "gpar")) gp_labels <- list(gp_labels) gp_labels <- pexpand(gp_labels, ld, list(gpar(fontsize = 12)), dn) ## varnames varnames <- pexpand(varnames, ld, labels, dn) ## tl_varnames if (is.null(tl_varnames) && is.null(labbl_varnames)) tl_varnames <- tl_labels tl_varnames <- pexpand(tl_varnames, ld, tl_labels, dn) ## labbl_varnames if (!is.null(labbl_varnames)) labbl_varnames <- pexpand(labbl_varnames, ld, TRUE, dn) ## boxes boxes <- pexpand(boxes, ld, FALSE, dn) ## fill_boxes dnl <- sapply(d, length) fill_boxes <- if (is.atomic(fill_boxes)) { fill_boxes <- if (is.logical(fill_boxes)) ifelse(pexpand(fill_boxes, ld, FALSE, dn), "grey", NA) else pexpand(fill_boxes, ld, "grey", dn) col <- rgb2hsv(col2rgb(fill_boxes)) lapply(seq(along.with = dnl), function(i) if (is.na(fill_boxes[i])) "white" else hsv(h = col["h",i], s = col["s",i], v = seq(from = col["v",i], to = 0.5 * col["v",i], length.out = dnl[i]) ) ) } else { fill_boxes <- pexpand(fill_boxes, ld, "white", dn) lapply(seq(ld), function(i) pexpand(fill_boxes[[i]], dnl[i], "white", d[[i]]) ) } ## precompute spaces lsp <- tsp <- bsp <- rsp <- 0 labsp <- rep.int(0, ld) for (i in seq_along(dn)[tl_labels & labels]) labsp[i] <- if (split_vertical[i]) { if (alternate_labels[i]) bsp <- bsp - 1 tsp <- tsp + 1 } else { if (alternate_labels[i]) rsp <- rsp + 1 lsp <- lsp - 1 } for (i in rev(seq_along(dn)[!tl_labels & labels])) labsp[i] <- if (split_vertical[i]) { if (alternate_labels[i]) tsp <- tsp + 1 bsp <- bsp - 1 } else { if (alternate_labels[i]) lsp <- lsp - 1 rsp <- rsp + 1 } if(is.null(labbl_varnames)) { ## varnames in the outer margin ## compute axis names tt <- bt <- lt <- rt <- "" for (i in seq_along(dn)) { var <- if (!is.null(set_varnames) && !is.na(set_varnames[dn[i]])) set_varnames[dn[i]] else dn[i] if (varnames[i]) { if (split_vertical[i]) { if (tl_varnames[i]) tt <- paste(tt, var, sep = if (tt == "") "" else " / ") else bt <- paste(bt, var, sep = if (bt == "") "" else " / ") } else { if (tl_varnames[i]) lt <- paste(lt, var, sep = if (lt == "") "" else " / ") else rt <- paste(rt, var, sep = if (rt == "") "" else " / ") } } } ## draw axis names if (tt != "") grid.text(tt, y = unit(1, "npc") + unit(tsp + 1, "lines") + offset_varnames[1], x = switch(pos_varnames[1], left =, bottom = 0, center =, centre = 0.5, 1), rot = rot_varnames[1], just = just_varnames[1], gp = gp_varnames[[1]]) if (bt != "") grid.text(bt, y = unit(bsp - 1, "lines") + -1 * offset_varnames[3], x = switch(pos_varnames[3], left =, bottom = 0, center =, centre = 0.5, 1), rot = rot_varnames[3], just = just_varnames[3], gp = gp_varnames[[3]]) if (lt != "") grid.text(lt, x = unit(lsp - 1, "lines") + -1 * offset_varnames[4], y = switch(pos_varnames[4], left =, bottom = 0, center =, centre = 0.5, 1), rot = rot_varnames[4], just = just_varnames[4], gp = gp_varnames[[4]]) if (rt != "") grid.text(rt, x = unit(1, "npc") + unit(rsp + 1, "lines") + offset_varnames[2], y = switch(pos_varnames[2], left =, bottom = 0, center =, centre = 0.5, 1), rot = rot_varnames[2], just = just_varnames[2], gp = gp_varnames[[2]]) } else { ## varnames beneath labels for (i in seq_along(dn)) { var <- if (!is.null(set_varnames) && !is.na(set_varnames[dn[i]])) set_varnames[dn[i]] else dn[i] if (varnames[i]) { if (split_vertical[i]) { if (tl_labels[i]) { if (labbl_varnames[i]) { grid.text(var, y = unit(1, "npc") + unit(1 + tsp - labsp[i], "lines") + offset_varnames[1], x = unit(-0.5, "lines"), just = "right", gp = gp_varnames[[4]]) } else { grid.text(var, y = unit(1, "npc") + unit(1 + tsp - labsp[i], "lines") + offset_varnames[1], x = unit(1, "npc") + unit(0.5, "lines"), just = "left", gp = gp_varnames[[2]]) } } else { if (labbl_varnames[i]) { grid.text(var, y = unit(labsp[i], "lines") + -1 * offset_varnames[3], x = unit(-0.5, "lines"), just = "right", gp = gp_varnames[[4]]) } else { grid.text(var, y = unit(labsp[i], "lines") + -1 * offset_varnames[3], x = unit(1, "npc") + unit(0.5, "lines"), just = "left", gp = gp_varnames[[2]]) } } } else { if (tl_labels[i]) { if (labbl_varnames[i]) { grid.text(var, x = unit(lsp - 1 - labsp[i], "lines") + -1 * offset_varnames[4], y = unit(-0.5, "lines"), just = "right", rot = 90, gp = gp_varnames[[4]]) } else { grid.text(var, x = unit(lsp - 1 - labsp[i], "lines") + -1 * offset_varnames[4], y = unit(1, "npc") + unit(0.5, "lines"), just = "left", rot = 90, gp = gp_varnames[[2]]) } } else { if (labbl_varnames[i]) { grid.text(var, x = unit(1, "npc") + unit(labsp[i], "lines") + offset_varnames[2], y = unit(-0.5, "lines"), just = "right", rot = 90, gp = gp_varnames[[4]]) } else { grid.text(var, x = unit(1, "npc") + unit(labsp[i], "lines") + offset_varnames[2], y = unit(1, "npc") + unit(0.5, "lines"), just = "left", rot = 90, gp = gp_varnames[[2]]) } } } } } } ## draw labels split <- function(vind = 1, root = paste(prefix, "cell:", sep = ""), left = TRUE, right = TRUE, top = TRUE, bottom = TRUE) { n <- d[[vind]] vl <- length(n) sp <- split_vertical[vind] labseq <- seq_along(n) if (!sp) labseq <- rev(labseq) for (labind in labseq) { mlab <- paste(root, dn[vind], "=", n[labind], sep = "") if (labels[vind] && (rep[vind] || !printed[[vind]][labind])) { lab <- if (!is.null(set_labels) && !is.null(set_labels[[dn[vind]]])) set_labels[[dn[vind]]][labind] else labs[[vind]][labind] if (labels_varnames[vind]) lab <- if (!is.null(set_varnames) && !is.na(set_varnames[dn[vind]])) paste(set_varnames[dn[vind]], lab, sep = sep) else paste(dn[vind], lab, sep = sep) if (sp) { if (tl_labels[vind]) { if (top) { seekViewport(mlab) if (clip[vind]) pushViewport(viewport(height = unit(1, "npc") + 2 * offset_labels[1] + unit(2 * (2 + tsp - labsp[vind]), "lines"), clip = "on")) if (boxes[vind]) grid.rect(height = unit(0.8, "lines"), y = unit(1, "npc") + offset_labels[1] + unit(1 + tsp - labsp[vind] - (2 + as.numeric(offset_labels[1]) + tsp - labsp[vind]) * clip[vind], "lines"), gp = gpar(fill = fill_boxes[[vind]][labind])) grid.text(lab, y = unit(1, "npc") + offset_labels[1] + unit(1 + tsp - labsp[vind] - (2 + as.numeric(offset_labels[1]) + tsp - labsp[vind]) * clip[vind], "lines"), x = unit(0.15 * switch(pos_labels[1], left =, bottom = 1, center =, centre = 0, -1) * boxes[vind], "lines") + unit(switch(pos_labels[1], left =, bottom = 0, center =, centre = 0.5, 1), "npc"), rot = rot_labels[1], just = just_labels[1], gp = gp_labels[[vind]]) if (clip[vind]) popViewport() printed[[vind]][labind] <<- TRUE } } else { if (bottom) { seekViewport(mlab) if (clip[vind]) pushViewport(viewport(height = unit(1, "npc") + 2 * offset_labels[3] + unit(2 * (1 + abs(labsp[vind])), "lines"), clip = "on")) ### if (boxes[vind]) grid.rect(height = unit(0.8, "lines"), y = -1 * offset_labels[3] + unit(labsp[vind] + (1 + as.numeric(offset_labels[3]) + abs(labsp[vind])) * clip[vind], "lines"), gp = gpar(fill = fill_boxes[[vind]][labind])) grid.text(lab, y = -1 * offset_labels[3] + unit(labsp[vind] + (1 + as.numeric(offset_labels[3]) + abs(labsp[vind])) * clip[vind], "lines"), x = unit(0.15 * switch(pos_labels[3], left =, bottom = 1, center =, centre = 0, -1) * boxes[vind], "lines") + unit(switch(pos_labels[3], left =, bottom = 0, center =, centre = 0.5, 1), "npc"), rot = rot_labels[3], just = just_labels[3], gp = gp_labels[[vind]]) if (clip[vind]) popViewport() printed[[vind]][labind] <<- TRUE } } } else { if (tl_labels[vind]) { if (left) { seekViewport(mlab) if (clip[vind]) pushViewport(viewport(width = unit(1, "npc") + 2 * offset_labels[4] + unit(2 * (2 - lsp + labsp[vind]), "lines"), clip = "on")) if (boxes[vind]) grid.rect(width = unit(0.8, "lines"), x = -1 * offset_labels[4] + unit(lsp - 1 - labsp[vind] + (2 - lsp + as.numeric(offset_labels[4]) + labsp[vind]) * clip[vind], "lines"), gp = gpar(fill = fill_boxes[[vind]][labind])) grid.text(lab, x = -1 * offset_labels[4] + unit(lsp - 1 - labsp[vind] + (2 - lsp + as.numeric(offset_labels[4]) + labsp[vind]) * clip[vind], "lines"), y = unit(0.15 * switch(pos_labels[4], left =, bottom = 1, centre = 0, -1) * boxes[vind], "lines") + unit(switch(pos_labels[4], left =, bottom = 0, center =, centre = 0.5, 1), "npc"), rot = rot_labels[4], just = just_labels[4], gp = gp_labels[[vind]]) if (clip[vind]) popViewport() printed[[vind]][labind] <<- TRUE } } else { if (right) { seekViewport(mlab) if (clip[vind]) pushViewport(viewport(width = unit(1, "npc") + 2 * offset_labels[2] + unit(2 * (1 + abs(labsp[vind])), "lines"), clip = "on")) if (boxes[vind]) grid.rect(width = unit(0.8, "lines"), x = offset_labels[2] + unit(1, "npc") + unit(labsp[vind] - (1 + as.numeric(offset_labels[2]) + abs(labsp[vind])) * clip[vind], "lines"), gp = gpar(fill = fill_boxes[[vind]][labind])) grid.text(lab, x = offset_labels[2] + unit(1, "npc") + unit(0.1, "lines") + unit(labsp[vind] - (1 + as.numeric(offset_labels[2]) + abs(labsp[vind])) * clip[vind], "lines"), y = unit(0.15 * switch(pos_labels[2], left =, bottom = 1, center =, centre = 0, -1) * boxes[vind], "lines") + unit(switch(pos_labels[2], left =, bottom = 0, center =, centre = 0.5, 1), "npc"), rot = rot_labels[2], just = just_labels[2], gp = gp_labels[[vind]]) if (clip[vind]) popViewport() printed[[vind]][labind] <<- TRUE } } } } if (vind < ld) Recall(vind + 1, paste(mlab, ",", sep = ""), if (sp) left && labind == 1 else left, if (sp) right && labind == vl else right, if (!sp) top && labind == 1 else top, if (!sp) bottom && labind == vl else bottom) } } ## patch for alternating labels, part 1 if (any(alternate_labels)) { ## save set_labels set_labels_hold <- set_labels ## create vanilla set_labels-object set_labels <- d ## copy old set_labels if (!is.null(set_labels_hold)) set_labels[names(set_labels_hold)] <- set_labels_hold ## mask half of the labels for (i in which(alternate_labels)) if (length(d[[i]]) > 1) set_labels[[i]][seq(2, length(d[[i]]), 2)] <- "" } split() ## patch for alternating labels, part 2 if (any(alternate_labels)) { ## create again vanilla set_labels-object set_labels <- d ## copy again old set_labels if (!is.null(set_labels_hold)) set_labels[names(set_labels_hold)] <- set_labels_hold ## clear all non-alternated labels labels[!alternate_labels] <- FALSE ## mask other half of alternated labels for (i in which(alternate_labels)) set_labels[[i]][seq(1, length(d[[i]]), 2)] <- "" ## invert tl_labels and labsp tl_labels <- ! tl_labels labsp <- -labsp ## label again split() } seekViewport(paste(prefix, "base", sep = "")) upViewport(1) } } class(labeling_border) <- "grapcon_generator" labeling_doubledecker <- function(lab_pos = c("bottom", "top"), dep_varname = TRUE, boxes = NULL, clip = NULL, labbl_varnames = FALSE, rot_labels = rep.int(0, 4), pos_labels = c("left", "center", "left", "center"), just_labels = c("left", "left", "left", "center"), varnames = NULL, gp_varnames = gpar(fontsize = 12, fontface = 2), offset_varnames = c(0, -0.6, 0, 0), tl_labels = NULL, ...) { lab_pos <- match.arg(lab_pos) if (inherits(gp_varnames, "gpar")) gp_varnames <- list(gp_varnames) gp_varnames <- pexpand(gp_varnames, 4, list(gpar(fontsize = 12, fontface = 2)), c("top", "right", "bottom", "left")) function(d, split_vertical, condvars, prefix = "") { if (is.table(d) || is.structable(d)) d <- dimnames(d) ld <- length(d) dn <- names(d) ## expand dimension parameters boxes <- pexpand(boxes, ld, c(rep.int(TRUE, ld - 1), FALSE), dn) clip <- pexpand(clip, ld, c(rep.int(TRUE, ld - 1), FALSE), dn) varnames <- pexpand(varnames, ld, c(rep.int(TRUE, ld - 1), FALSE), dn) tl_labels <- pexpand(tl_labels, ld, c(rep.int(lab_pos == "top", ld - 1), FALSE), dn) if (!is.null(labbl_varnames)) labbl_varnames <- pexpand(labbl_varnames, ld, FALSE, dn) ## expand side parameters rot_labels <- pexpand(rot_labels, 4, c(0, 0, 0, 0), c("top", "right", "bottom", "left")) pos_labels <- pexpand(pos_labels, 4, c("left", "center", "left", "center"), c("top", "right", "bottom", "left"), c("left", "center", "right")) just_labels <- pexpand(just_labels, 4, c("left", "left", "left", "center"), c("top", "right", "bottom", "left"), c("left", "center", "right")) offset_varnames <- if (!is.unit(offset_varnames)) unit(pexpand(offset_varnames, 4, c(0, -0.6, 0, 0), c("top","right","bottom","left")), "lines") else rep(offset_varnames, length.out = 4) labeling_border(boxes = boxes, clip = clip, labbl_varnames = labbl_varnames, rot_labels = rot_labels, pos_labels = pos_labels, just_labels = just_labels, varnames = varnames, gp_varnames = gp_varnames, offset_varnames = offset_varnames, tl_labels = tl_labels, ... )(d, split_vertical, condvars, prefix) if (!(is.logical(dep_varname) && !dep_varname)) { if (is.null(dep_varname) || is.logical(dep_varname)) dep_varname <- names(d)[length(d)] seekViewport(paste(prefix, "margin_right", sep = "")) grid.text(dep_varname, x = unit(0.5, "lines"), y = unit(1, "npc"), just = c("left","top"), gp = gp_varnames[[2]]) } } } class(labeling_doubledecker) <- "grapcon_generator" labeling_left <- function(rep = FALSE, pos_varnames = "left", pos_labels = "left", just_labels = "left", ...) labeling_border(rep = rep, pos_varnames = pos_varnames, pos_labels = pos_labels, just_labels = just_labels, ...) class(labeling_left) <- "grapcon_generator" labeling_left2 <- function(tl_labels = TRUE, clip = TRUE, pos_varnames = "left", pos_labels = "left", just_labels = "left", ...) labeling_border(tl_labels = tl_labels, clip = clip, pos_varnames = pos_varnames, pos_labels = pos_labels, just_labels = just_labels, ...) class(labeling_left2) <- "grapcon_generator" labeling_cboxed <- function(tl_labels = TRUE, boxes = TRUE, clip = TRUE, pos_labels = "center", ...) labeling_border(tl_labels = tl_labels, boxes = boxes, clip = clip, pos_labels = pos_labels, ...) class(labeling_cboxed) <- "grapcon_generator" labeling_lboxed <- function(tl_labels = FALSE, boxes = TRUE, clip = TRUE, pos_labels = "left", just_labels = "left", labbl_varnames = FALSE, ...) labeling_border(tl_labels = tl_labels, boxes = boxes, clip = clip, pos_labels = pos_labels, labbl_varnames = labbl_varnames, just_labels = just_labels, ...) class(labeling_lboxed) <- "grapcon_generator" labeling_values <- function(value_type = c("observed", "expected", "residuals"), suppress = NULL, digits = 1, clip_cells = FALSE, ...) { value_type <- match.arg(value_type) if (value_type == "residuals" && is.null(suppress)) suppress <- 2 if (is.null(suppress)) suppress <- 0 if (length(suppress) == 1) suppress <- c(-suppress, suppress) function(d, split_vertical, condvars, prefix) { lookup <- if (value_type == "observed") "x" else value_type if (!exists(lookup, envir = parent.frame())) stop(paste("Could not find", dQuote(value_type), "object.")) values <- get(lookup, envir = parent.frame()) values <- ifelse((values > suppress[2]) | (values < suppress[1]), round(values, digits), NA) labeling_border(...)(d, split_vertical, condvars, prefix) labeling_cells(text = values, clip_cells = clip_cells, ...)(d, split_vertical, condvars, prefix) } } class(labeling_values) <- "grapcon_generator" labeling_residuals <- function(suppress = NULL, digits = 1, clip_cells = FALSE, ...) labeling_values(value_type = "residuals", suppress = suppress, digits = digits, clip_cells = clip_cells, ...) class(labeling_residuals) <- "grapcon_generator"
/scratch/gouwar.j/cran-all/cranData/vcd/R/labeling.R
legend_resbased <- function(fontsize = 12, fontfamily = "", x = unit(1, "lines"), y = unit(0.1, "npc"), height = unit(0.8, "npc"), width = unit(0.7, "lines"), digits = 2, pdigits = max(1, getOption("digits") - 2), check_overlap = TRUE, text = NULL, steps = 200, ticks = 10, pvalue = TRUE, range = NULL) { if(!is.unit(x)) x <- unit(x, "native") if(!is.unit(y)) y <- unit(y, "npc") if(!is.unit(width)) width <- unit(width, "lines") if(!is.unit(height)) height <- unit(height, "npc") function(residuals, shading, autotext) { res <- as.vector(residuals) if(is.null(text)) text <- autotext p.value <- attr(shading, "p.value") legend <- attr(shading, "legend") if (all(residuals == 0)) { pushViewport(viewport(x = x, y = y, just = c("left", "bottom"), default.units = "native", height = height, width = width)) grid.lines(y = 0.5) grid.text(0, x = unit(1, "npc") + unit(0.8, "lines"), y = 0.5, gp = gpar(fontsize = fontsize, fontfamily = fontfamily)) warning("All residuals are zero.") } else { if (is.null(range)) range <- range(res) if (length(range) != 2) stop("Range must have length two!") if (is.na(range[1])) range[1] <- min(res) if (is.na(range[2])) range[2] <- max(res) pushViewport(viewport(x = x, y = y, just = c("left", "bottom"), yscale = range, default.units = "native", height = height, width = width)) if(is.null(legend$col.bins)) { col.bins <- seq(range[1], range[2], length.out = steps) at <- NULL } else { col.bins <- sort(unique(c(legend$col.bins, range))) col.bins <- col.bins[col.bins <= range[2] & col.bins >= range[1]] at <- col.bins } y.pos <- col.bins[-length(col.bins)] y.height <- diff(col.bins) grid.rect(x = unit(rep.int(0, length(y.pos)), "npc"), y = y.pos, height = y.height, default.units = "native", gp = gpar(fill = shading(y.pos + 0.5 * y.height)$fill, col = 0), just = c("left", "bottom")) grid.rect(gp = gpar(fill = "transparent")) if(is.null(at)) at <- seq(from = head(col.bins, 1), to = tail(col.bins, 1), length.out = ticks) lab <- format(round(at, digits = digits), nsmall = digits) tw <- lab[which.max(nchar(lab))] ## if(is.null(at)) ## at <- seq(from = head(col.bins, 1), to = tail(col.bins, 1), length = ticks) ## tw <- paste(rep("4", digits), collapse = "") ## if (any(trunc(at) != at)) ## tw <- paste(tw, ".", sep = "") ## if (any(at < 0)) ## tw <- paste(tw, "-", sep = "") grid.text(format(signif(at, digits = digits)), x = unit(1, "npc") + unit(0.8, "lines") + unit(1, "strwidth", tw), y = at, default.units = "native", just = c("right", "center"), gp = gpar(fontsize = fontsize, fontfamily = fontfamily), check.overlap = check_overlap) grid.segments(x0 = unit(1, "npc"), x1 = unit(1,"npc") + unit(0.5, "lines"), y0 = at, y1 = at, default.units = "native") } popViewport(1) grid.text(text, x = x, y = unit(1, "npc") - y + unit(1, "lines"), gp = gpar(fontsize = fontsize, fontfamily = fontfamily, lineheight = 0.8), just = c("left", "bottom") ) if(!is.null(p.value) && pvalue) { grid.text(paste("p-value =\n", format.pval(p.value, digits = pdigits), sep = ""), x = x, y = y - unit(1, "lines"), gp = gpar(fontsize = fontsize, fontfamily = fontfamily, lineheight = 0.8), just = c("left", "top")) } } } class(legend_resbased) <- "grapcon_generator" legend_fixed <- function(fontsize = 12, fontfamily = "", x = unit(1, "lines"), y = NULL, height = NULL, width = unit(1.5, "lines"), steps = 200, digits = 1, space = 0.05, text = NULL, range = NULL) { if(!is.unit(x)) x <- unit(x, "native") if(!is.unit(y) && !is.null(y)) y <- unit(y, "npc") if(!is.unit(width)) width <- unit(width, "lines") if(!is.unit(height) && !is.null(height)) height <- unit(height, "npc") function(residuals, shading, autotext) { res <- as.vector(residuals) if(is.null(text)) text <- autotext if (is.null(y)) y <- unit(1, "strwidth", text) + unit(1, "lines") if (is.null(height)) height <- unit(1, "npc") - y pushViewport(viewport(x = x, y = y, just = c("left", "bottom"), yscale = c(0,1), default.units = "npc", height = height, width = width)) p.value <- attr(shading, "p.value") legend <- attr(shading, "legend") if (is.null(range)) range <- range(res) if (length(range) != 2) stop("Range must have length two!") if (is.na(range[1])) range[1] <- min(res) if (is.na(range[2])) range[2] <- max(res) if(is.null(legend$col.bins)) { col.bins <- seq(range[1], range[2], length.out = steps) } else { col.bins <- sort(unique(c(legend$col.bins, range))) col.bins <- col.bins[col.bins <= range[2] & col.bins >= range[1]] } l <- length(col.bins) y.height <- (1 - (l - 2) * space) / (l - 1) y.pos <- cumsum(c(0, rep(y.height + space, l - 2))) res <- col.bins[-l] + diff(col.bins) / 2 grid.rect(x = unit(rep.int(0, length(y.pos)), "npc"), y = y.pos, height = y.height, default.units = "npc", gp = shading(res), just = c("left", "bottom")) numbers <- format(col.bins, nsmall = digits, digits = digits) wid <- unit(1, "strwidth", format(max(abs(col.bins)), nsmall = digits, digits = digits)) grid.text(numbers[-l], x = unit(1, "npc") + unit(0.6, "lines") + wid, y = y.pos, gp = gpar(fontsize = fontsize, fontfamily = fontfamily), default.units = "npc", just = c("right", "bottom")) grid.text(numbers[-1], x = unit(1, "npc") + unit(0.6, "lines") + wid, y = y.pos + y.height, gp = gpar(fontsize = fontsize, fontfamily = fontfamily), default.units = "npc", just = c("right", "top")) wid2 <- unit(1, "strwidth", format(max(abs(trunc(col.bins))))) + unit(0.3, "strwidth", ".") grid.segments(x0 = unit(1, "npc") + wid2 + unit(0.6, "lines"), x1 = unit(1, "npc") + wid2 + unit(0.6, "lines"), y0 = unit(y.pos, "npc") + 1.5 * unit(1, "strheight", "-44.4"), y1 = unit(y.pos + y.height, "npc") - 1.5 * unit(1, "strheight", "-44.4") ) popViewport(1) grid.text(text, x = x + 0.5 * width, y = 0, gp = gpar(fontsize = fontsize, fontfamily = fontfamily, lineheight = 0.8), just = c("left", "top"), rot = 90 ) } } class(legend_fixed) <- "grapcon_generator"
/scratch/gouwar.j/cran-all/cranData/vcd/R/legends.R
odds <- function(x, log = FALSE, ...) lodds(x, log = log, ...) lodds <- function(x, ...) UseMethod("lodds") lodds.formula <- function(formula, data = NULL, ..., subset = NULL, na.action = NULL) { m <- match.call(expand.dots = FALSE) edata <- eval(m$data, parent.frame()) fstr <- strsplit(paste(deparse(formula), collapse = ""), "~") vars <- strsplit(strsplit(gsub(" ", "", fstr[[1]][2]), "\\|")[[1]], "\\+") varnames <- vars[[1]] condnames <- if (length(vars) > 1) vars[[2]] else NULL dep <- gsub(" ", "", fstr[[1]][1]) if (!dep %in% c("","Freq")) { if (all(varnames == ".")) { varnames <- if (is.data.frame(data)) colnames(data) else names(dimnames(as.table(data))) varnames <- varnames[-which(varnames %in% dep)] } varnames <- c(dep, varnames) } if (inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) { condind <- NULL dat <- as.table(data) if(all(varnames != ".")) { ind <- match(varnames, names(dimnames(dat))) if (any(is.na(ind))) stop(paste("Can't find", paste(varnames[is.na(ind)], collapse=" / "), "in", deparse(substitute(data)))) if (!is.null(condnames)) { condind <- match(condnames, names(dimnames(dat))) if (any(is.na(condind))) stop(paste("Can't find", paste(condnames[is.na(condind)], collapse=" / "), "in", deparse(substitute(data)))) ind <- c(ind, condind) } dat <- margin.table(dat, ind) } lodds.default(dat, strata = if (is.null(condind)) NULL else match(condnames, names(dimnames(dat))), ...) } else { m <- m[c(1, match(c("formula", "data", "subset", "na.action"), names(m), 0))] m[[1]] <- as.name("xtabs") m$formula <- formula(paste(if("Freq" %in% colnames(data)) "Freq", "~", paste(c(varnames, condnames), collapse = "+"))) tab <- eval(m, parent.frame()) lodds.default(tab, ...) } } lodds.default <- function(x, response = NULL, strata = NULL, log = TRUE, ref = NULL, correct = any(x == 0), ...) { ## check dimensions L <- length(d <- dim(x)) if(any(d < 2L)) stop("All table dimensions must be 2 or greater") ## assign and check response and stata; convert variable names to indices if (is.null(response)) { if (is.null(strata)) { response <- 1 strata <- setdiff(1:L, response) } else { # only strata was specified if(L - length(strata) != 1L) stop("All but 1 dimension must be specified as strata.") if(is.character(strata)) strata <- which(names(dimnames(x)) == strata) response <- setdiff(1:L, strata) } } else { # response was specified; take strata as the complement if(length(response) > 1) stop("Only 1 dimension can be specified as a response") if(is.character(response)) response <- which(names(dimnames(x)) == response) if (!is.null(strata)) warning(paste("strata =", paste(strata, collapse=","), "ignored when response has been specified")) strata <- setdiff(1:L, response) } ## dimensions of primary R x 1 table ### [Or should this just be a vector???] dp <- if (length(strata)) d[response] else d dn <- if (length(strata)) dimnames(x)[response] else dimnames(x) R <- dp[1] C <- 1 # shadow matrix with proper dimnames X <- matrix(0, R, C, dimnames=dn) ## process reference category if(!is.null(ref)) { if(is.character(ref)) { ref <- match(ref, colnames(x)) } else if(is.numeric(ref)) { ref <- as.integer(ref) } else { stop("Wrong 'ref=' argument!") } } ## compute corresponding indices compute_index <- function(n, ref) { if(is.null(ref)) return(cbind(1:(n-1), 2:n)) rval <- cbind(ref, 1:n) d <- rval[,2L] - rval[,1L] rval <- rbind( rval[d > 0, 1:2], rval[d < 0, 2:1] ) return(rval[order(rval[,1L]),,drop = FALSE]) } Rix <- compute_index(R, ref[[1L]]) contr <- matrix(0L, nrow = (R-1), ncol = R) colnames(contr) <- rownames(X) rownames(contr) <- rep("", R-1) for(i in 1:(R-1)) { rix <- i cix <- Rix[i,] contr[rix, cix] <- c(1L, -1L) rownames(contr)[rix] <- paste(rownames(X)[Rix[i,]], collapse = ":") } ## handle strata if (!is.null(strata)) { if (length(strata)==1) { sn <- dimnames(x)[[strata]] } else { sn <- apply(expand.grid(dimnames(x)[strata]), 1, paste, collapse = ":") } rn <- as.vector(outer( dimnames(contr)[[1]], sn, paste, sep='|')) cn <- as.vector(outer( dimnames(contr)[[2]], sn, paste, sep='|')) contr <- kronecker(diag(prod(dim(x)[strata])), contr) rownames(contr) <- rn colnames(contr) <- cn } ## dimnames for array version dn <- list(rep("", R-1)) for(i in 1:(R-1)) dn[[1]][i] <- paste(rownames(X)[Rix[i,]], collapse = ":") if (!is.null(strata)) dn <- c(dn, dimnames(x)[strata]) ndn <- names(dimnames(x)) if (!is.null(names(dimnames(x)))) names(dn) <- c(ndn[response], ndn[strata]) ## point estimates if (is.logical(correct)) { add <- if(correct) 0.5 else 0 } else if(is.numeric(correct)) { add <- as.vector(correct) if (length(add) != length(x)) stop("array size of 'correct' does not conform to the data") } else stop("correct is not valid") ## reorder columns of contrast matrix to match original data contr <- contr[, order(as.vector(aperm(array(seq.int(prod(d)), d), c(response, strata))))] ##coef <- drop(contr %*% log(as.vector(x) + add)) ##FIXME: 0 cells mess up the matrix product, try workaround: mat <- log(as.vector(x) + add) * t(contr) nas <- apply(contr != 0 & is.na(t(mat)), 1, any) coef <- apply(mat, 2, sum, na.rm = TRUE) coef[nas] <- NA ## covariances ##vcov <- crossprod(diag(sqrt(1/(as.vector(x) + add))) %*% t(contr)) tmp <- sqrt(1/(as.vector(x) + add)) * t(contr) tmp[is.na(tmp)] <- 0 vcov <- crossprod(tmp) vcov[nas,] <- NA vcov[,nas] <- NA rval <- structure(list( response = response, strata = strata, coefficients = coef, dimnames = dn, dim = as.integer(sapply(dn, length)), vcov = vcov, contrasts = contr, log = log ), class = "lodds") rval } ## ---------------- Methods ------------------- summary.lodds <- function(object, ...) lmtest::coeftest(object, ...) ## dim methods dimnames.lodds <- function(x, ...) x$dimnames dim.lodds <- function(x, ...) x$dim ## t/aperm-methods t.lodds <- function(x) aperm(x) ### FIXME aperm.lodds <- function(a, perm = NULL, ...) { d <- length(a$dim) if(is.null(perm)) { perm <- if (d < 3) 2L : 1L else c(2L : 1L, d : 3L) } else { if (any(perm[1:2] > 2L) || (d > 2L) && any(perm[-c(1:2)] < 2L)) stop("Mixing of strata and non-strata variables not allowed!") } nams <- names(a$coefficients) a$coefficients <- as.vector(aperm(array(a$coef, dim = a$dim), perm, ...)) nams <- as.vector(aperm(array(nams, dim = a$dim), perm, ...)) names(a$coefficients) <- nams a$dimnames <- a$dimnames[perm] a$dim <- a$dim[perm] a$vcov <- a$vcov[nams, nams] a$contrasts <- a$contrasts[nams,] a } ## straightforward methods coef.lodds <- function(object, log = object$log, ...) if(log) object$coefficients else exp(object$coefficients) vcov.lodds <- function(object, log = object$log, ...) if(log) object$vcov else `diag<-`(object$vcov, diag(object$vcov) * exp(object$coefficients)^2) confint.lodds <- function(object, parm, level = 0.95, log = object$log, ...) { if (log) confint.default(object, parm = parm, level = level, ... ) else { object$log = TRUE exp(confint.default(object, parm = parm, level = level, ... )) } } ### DONE: ## The header should say: # (log) odds for vn[response] by ... all the rest (strata) # Fixed: clash with make_header in loddsratio make_header_odds <- function(x) { vn <- names(dimnames(x)) resp <- vn[x$response] strat <- paste(vn[x$strata], collapse=", ") header <- c(if(x$log) "log" else "", "odds for", resp, "by", strat, # if (length(vn)>2) c("by", paste(vn[-(1:2)], collapse=', ')), "\n\n") paste(header, sep = " ") } ## print method print.lodds <- function(x, log = x$log, ...) { cat(make_header_odds(x)) print(drop(array(coef(x, log = log), dim = dim(x), dimnames = dimnames(x)), ...)) invisible(x) } ## as.data.frame #as.data.frame.lodds <- # function(x, ...) # as.data.frame.table(vcd:::as.array.loddsratio(x), ...) ## Q: I don't understand the purpose of the row.names and optional arguments ## DM: The generic has them, so each method must have them, too as.data.frame.lodds <- function(x, row.names = NULL, optional = FALSE, log=x$log, ...) { df <-data.frame(expand.grid(dimnames(x)), logodds = coef(x, log = log), ASE = sqrt(diag(vcov(x, log = log))), row.names = row.names, ... ) if (!log) colnames(df)[ncol(df) - 1] <- "odds" df } ## FIXME ## reshape coef() methods as.matrix.lodds <- function (x, log=x$log, ...) { ## Coef <- coef(x, log = log) ## if (length(dim(x))==2) matrix(Coef, ncol = dim(x)[2], dimnames=dimnames(x)) ## else { # drop leading dimensions with length 1, then reshape ## ddim <- which(dim(x)[1:2]==1) ## dim(Coef) <- dim(x)[-ddim] ## dimnames(Coef) <- dimnames(x)[-ddim] ## if (length(dim(Coef))==1) Coef ## else ## matrix(Coef, ncol = prod(dim(Coef)[-1]), ## dimnames=list(dimnames(Coef)[[1]], apply(expand.grid(dimnames(Coef)[[-1]]), 1, paste, collapse = ":"))) ## } as.array(x, log = log, ...) } as.array.lodds <- function (x, log=x$log, ...) { res <- array(coef(x, log = log), dim = dim(x), dimnames=dimnames(x)) drop(res) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/lodds.R
## Modifications: ## -- return a dnames component, containing dimnames for the array version of coef ## -- added dim methods: dim.loddsratio, dimnames.loddsratio ## -- added print.loddsratio ## -- handle strata: result computed correctly, but structure of coef() loses names ## and confint doesn't work in the 2x2xk or RxCxk case ## -- Fixed problem with strata by setting rownames and colnames for contrast matrix ## DONE: handle multiple strata (|foo:bar) ## -- print.loddsratio now uses drop() for dimensions of length 1 ## -- made generic, anticipating a formula method, maybe structable or ftable methods ## DONE: decide which methods should allow a log=FALSE argument to provide exp(lor) ## -- Now handle any number of strata ## -- Added log= argument to print, coef methods, and added confint.loddsratio method, ## allowing log=FALSE ## -- Incorporated Z code additions, fixing some <FIXME>s ## -- Added as.matrix and as.array methods; had to make as.array S3 generic ## -- Added header to print method ## -- Added as.data.frame method (for use in plots) ## -- "LOR" is renamed "OR" if log=FALSE ## -- Revised as.matrix to drop leading 1:2 dimensions of length 1 ## -- Removed as.array generic, now in base ## -- DM: added plot.oddsratio method ## -- DM: added formula interface ## -- DM: add t() and aperm() methdos loddsratio <- function(x, ...) UseMethod("loddsratio") loddsratio.formula <- function(formula, data = NULL, ..., subset = NULL, na.action = NULL) { m <- match.call(expand.dots = FALSE) edata <- eval(m$data, parent.frame()) fstr <- strsplit(paste(deparse(formula), collapse = ""), "~") vars <- strsplit(strsplit(gsub(" ", "", fstr[[1]][2]), "\\|")[[1]], "\\+") varnames <- vars[[1]] condnames <- if (length(vars) > 1) vars[[2]] else NULL dep <- gsub(" ", "", fstr[[1]][1]) if (!dep %in% c("","Freq")) { if (all(varnames == ".")) { varnames <- if (is.data.frame(data)) colnames(data) else names(dimnames(as.table(data))) varnames <- varnames[-which(varnames %in% dep)] } varnames <- c(dep, varnames) } if (inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) { condind <- NULL dat <- as.table(data) if(all(varnames != ".")) { ind <- match(varnames, names(dimnames(dat))) if (any(is.na(ind))) stop(paste("Can't find", paste(varnames[is.na(ind)], collapse=" / "), "in", deparse(substitute(data)))) if (!is.null(condnames)) { condind <- match(condnames, names(dimnames(dat))) if (any(is.na(condind))) stop(paste("Can't find", paste(condnames[is.na(condind)], collapse=" / "), "in", deparse(substitute(data)))) ind <- c(ind, condind) } dat <- margin.table(dat, ind) } loddsratio.default(dat, strata = if (is.null(condind)) NULL else match(condnames, names(dimnames(dat))), ...) } else { m <- m[c(1, match(c("formula", "data", "subset", "na.action"), names(m), 0))] m[[1]] <- as.name("xtabs") m$formula <- formula(paste(if("Freq" %in% colnames(data)) "Freq", "~", paste(c(varnames, condnames), collapse = "+"))) tab <- eval(m, parent.frame()) loddsratio.default(tab, ...) } } loddsratio.default <- function(x, strata = NULL, log = TRUE, ref = NULL, correct = any(x == 0), ...) { ## check dimensions L <- length(d <- dim(x)) if(any(d < 2L)) stop("All table dimensions must be 2 or greater") if(L > 2L && is.null(strata)) strata <- 3L:L if(is.character(strata)) strata <- which(names(dimnames(x)) == strata) if(L - length(strata) != 2L) stop("All but 2 dimensions must be specified as strata.") ## dimensions of primary R x C table dp <- if (length(strata)) d[-strata] else d dn <- if (length(strata)) dimnames(x)[-strata] else dimnames(x) R <- dp[1] C <- dp[2] # shadow matrix with proper dimnames X <- matrix(0, R, C, dimnames=dn) ## process reference categories (always return list of length ## two with reference for rows/cols, respectively) if(is.null(ref)) { ref <- list(NULL, NULL) } else if(is.character(ref)) { if(length(ref) != 2L) stop("'ref' must specify both reference categories") ref <- list(match(ref[1L], rownames(x)), match(ref[2L], colnames(x))) } else if(is.numeric(ref)) { ref <- as.integer(rep(ref, length.out = 2L)) ref <- list(ref[1L], ref[2L]) } ## compute corresponding indices compute_index <- function(n, ref) { if(is.null(ref)) return(cbind(1:(n-1), 2:n)) rval <- cbind(ref, 1:n) d <- rval[,2L] - rval[,1L] rval <- rbind( rval[d > 0, 1:2], rval[d < 0, 2:1] ) return(rval[order(rval[,1L]),,drop = FALSE]) } Rix <- compute_index(R, ref[[1L]]) Cix <- compute_index(C, ref[[2L]]) ## set up contrast matrix for the primary R x C table contr <- matrix(0L, nrow = (R-1) * (C-1), ncol = R * C) colnames(contr) <- paste(rownames(X)[as.vector(row(X))], colnames(X)[as.vector(col(X))], sep = ":") rownames(contr) <- rep("", (R-1) * (C-1)) for(i in 1:(R-1)) for(j in 1:(C-1)) { rix <- (j-1) * (R-1) + i cix <- rep(Rix[i,], 2L) + R * (rep(Cix[j,], each = 2L) - 1L) contr[rix, cix] <- c(1L, -1L, -1L, 1L) if (R > 2 || C > 2 || is.null(strata)) rownames(contr)[rix] <- sprintf("%s/%s", paste(rownames(X)[Rix[i,]], collapse = ":"), paste(colnames(X)[Cix[j,]], collapse = ":")) } # handle strata if (!is.null(strata)) { if (length(strata)==1) { sn <- dimnames(x)[[strata]] } else { sn <- apply(expand.grid(dimnames(x)[strata]), 1, paste, collapse = ":") } SEP <- if (R > 2 || C > 2 || is.null(strata)) "|" else "" rn <- as.vector(outer( dimnames(contr)[[1]], sn, paste, sep=SEP)) cn <- as.vector(outer( dimnames(contr)[[2]], sn, paste, sep=SEP)) contr <- kronecker(diag(prod(dim(x)[strata])), contr) rownames(contr) <- rn colnames(contr) <- cn } ## dimnames for array version dn <- list(rep("", R-1), rep("", C-1)) for(i in 1:(R-1)) dn[[1]][i] <- paste(rownames(x)[Rix[i,]], collapse = ":") for(j in 1:(C-1)) dn[[2]][j] <- paste(colnames(x)[Cix[j,]], collapse = ":") if (!is.null(strata)) dn <- c(dn, dimnames(x)[strata]) if (!is.null(names(dimnames(x)))) names(dn) <- names(dimnames(x)) ## point estimates if (is.logical(correct)) { add <- if(correct) 0.5 else 0 } else if(is.numeric(correct)) { add <- as.vector(correct) if (length(add) != length(x)) stop("array size of 'correct' does not conform to the data") } else stop("correct is not valid") ##coef <- drop(contr %*% log(as.vector(x) + add)) ##FIXME: 0 cells mess up the matrix product, try workaround: mat <- log(as.vector(x) + add) * t(contr) nas <- apply(contr != 0 & is.na(t(mat)), 1, any) coef <- apply(mat, 2, sum, na.rm = TRUE) coef[nas] <- NA ## covariances ##vcov <- crossprod(diag(sqrt(1/(as.vector(x) + add))) %*% t(contr)) tmp <- sqrt(1/(as.vector(x) + add)) * t(contr) tmp[is.na(tmp)] <- 0 vcov <- crossprod(tmp) vcov[nas,] <- NA vcov[,nas] <- NA rval <- structure(list( coefficients = coef, dimnames = dn, dim = as.integer(sapply(dn, length)), vcov = vcov, contrasts = contr, log = log ), class = "loddsratio") rval } ## dim methods dimnames.loddsratio <- function(x, ...) x$dimnames dim.loddsratio <- function(x, ...) x$dim ## t/aperm-methods t.loddsratio <- function(x) aperm(x) aperm.loddsratio <- function(a, perm = NULL, ...) { d <- length(a$dim) if(is.null(perm)) { perm <- if (d < 3) 2L : 1L else c(2L : 1L, d : 3L) } else { if (any(perm[1:2] > 2L) || (d > 2L) && any(perm[-c(1:2)] < 2L)) stop("Mixing of strata and non-strata variables not allowed!") } nams <- names(a$coefficients) a$coefficients <- as.vector(aperm(array(a$coef, dim = a$dim), perm, ...)) nams <- as.vector(aperm(array(nams, dim = a$dim), perm, ...)) names(a$coefficients) <- nams a$dimnames <- a$dimnames[perm] a$dim <- a$dim[perm] a$vcov <- a$vcov[nams, nams] a$contrasts <- a$contrasts[nams,] a } ## straightforward methods coef.loddsratio <- function(object, log = object$log, ...) if(log) object$coefficients else exp(object$coefficients) vcov.loddsratio <- function(object, log = object$log, ...) if(log) object$vcov else `diag<-`(object$vcov, diag(object$vcov) * exp(object$coefficients)^2) confint.loddsratio <- function(object, parm, level = 0.95, log = object$log, ...) { if (log) confint.default(object, parm = parm, level = level, ... ) else { object$log = TRUE exp(confint.default(object, parm = parm, level = level, ... )) } } make_header <- function(x) { vn <- names(dimnames(x)) header <- c(if(x$log) "log" else "", "odds ratios for", vn[1], "and", vn[2], if (length(vn)>2) c("by", paste(vn[-(1:2)], collapse=', ')), "\n\n") paste(header, sep = " ") } ## print method print.loddsratio <- function(x, log = x$log, ...) { cat(make_header(x)) print(drop(array(coef(x, log = log), dim = dim(x), dimnames = dimnames(x)), ...)) invisible(x) } summary.loddsratio <- function(object, ...) lmtest::coeftest(object, ...) ## reshape coef() methods as.matrix.loddsratio <- function (x, log=x$log, ...) { Coef <- coef(x, log = log) if (length(dim(x))==2) matrix(Coef, ncol = dim(x)[2], dimnames=dimnames(x)) else { # drop leading dimensions with length 1, then reshape ddim <- which(dim(x)[1:2]==1) dim(Coef) <- dim(x)[-ddim] dimnames(Coef) <- dimnames(x)[-ddim] if (length(dim(Coef))==1) Coef else matrix(Coef, ncol = prod(dim(Coef)[-1]), dimnames=list(dimnames(Coef)[[1]], apply(expand.grid(dimnames(Coef)[[-1]]), 1, paste, collapse = ":"))) } } as.array.loddsratio <- function (x, log=x$log, ...) { res <- array(coef(x, log = log), dim = dim(x), dimnames=dimnames(x)) drop(res) } as.data.frame.loddsratio <- function(x, row.names = NULL, optional, log=x$log, ...) { df <-data.frame(expand.grid(dimnames(x)), LOR = coef(x, log=log), ASE = sqrt(diag(vcov(x, log=log))), row.names=row.names, ... ) if (!log) colnames(df)[ncol(df)-1] <- "OR" df } image.loddsratio <- function(x, interpolate = NULL, legend = legend_fixed, gp = shading_Friendly, gp_args = NULL, labeling = labeling_values("residuals", suppress = 0), perm = NULL, ...) { a <- as.array(x) if (!is.null(dim(a))) { if (is.null(perm)) { d <- seq_along(dim(a)) perm <- c(d[-c(1:2)], 1:2) } a <- aperm(a, perm) } else { a <- as.table(a) names(dimnames(a)) <- names(dimnames(x))[1] } if (is.null(interpolate)) interpolate <- seq(0.1, max(abs(a), length.out = 4)) if (is.null(gp_args)) gp_args <- list(interpolate = interpolate) tmp <- a tmp[] <- 1 mosaic(tmp, type = "expected", residuals = a, shade = TRUE, gp = shading_Friendly, gp_args = gp_args, legend = legend, labeling = labeling, ...) } tile.loddsratio <- function(x, interpolate = NULL, legend = legend_fixed, gp = shading_Friendly, gp_args = NULL, labeling = labeling_values("residuals", suppress = 0), halign = "center", valign = "center", perm = NULL, ...) { a <- as.array(x) if (!is.null(dim(a))) { if (is.null(perm)) { d <- seq_along(dim(a)) perm <- c(d[-c(1:2)], 1:2) } a <- aperm(a, perm) } else { a <- as.table(a) names(dimnames(a)) <- names(dimnames(x))[1] } if (is.null(interpolate)) interpolate <- seq(0.1, max(abs(a), length.out = 4)) if (is.null(gp_args)) gp_args <- list(interpolate = interpolate) tile(abs(a), halign = halign, valign = valign, residuals = a, shade = TRUE, gp = shading_Friendly, gp_args = gp_args, legend = legend, labeling = labeling, ...) } "plot.loddsratio" <- function(x, baseline = TRUE, gp_baseline = gpar(lty = 2), lines = TRUE, lwd_lines = 3, confidence = TRUE, conf_level = 0.95, lwd_confidence = 2, whiskers = 0, transpose = FALSE, col = NULL, cex = 0.8, pch = NULL, bars = NULL, gp_bars = gpar(fill = "lightgray", alpha = 0.5), bar_width = unit(0.05, "npc"), legend = TRUE, legend_pos = "topright", legend_inset = c(0, 0), legend_vgap = unit(0.5, "lines"), gp_legend_frame = gpar(lwd = 1, col = "black"), gp_legend_title = gpar(fontface = "bold"), gp_legend = gpar(), legend_lwd = 1, legend_size = 1, xlab = NULL, ylab = NULL, xlim = NULL, ylim = NULL, main = NULL, gp_main = gpar(fontsize = 12, fontface = "bold"), newpage = TRUE, pop = FALSE, return_grob = FALSE, add = FALSE, prefix = "", ...) { ## handle default values, limits etc. LOG <- x$log values <- as.array(x) d <- dim(values) if (is.null(bars)) bars <- is.null(d) oddsrange <- range(values, na.rm = TRUE) if(confidence) { CI <- confint(x, log = LOG, level = conf_level) lwr <- CI[,1] upr <- CI[,2] oddsrange <- if (baseline) c(min(0, lwr, na.rm = TRUE), max(0, upr, na.rm = TRUE)) else c(min(lwr, na.rm = TRUE), max(upr, na.rm = TRUE)) } if (is.null(main)) main <- paste(make_header(x), collapse = " ") if (is.null(xlim)) xlim <- if (is.null(d)) c(1, length(values)) else c(1, d[1]) if (is.null(ylim)) ylim <- oddsrange ylimaxis <- ylim + c(-1, 1) * diff(ylim) * 0.04 xlimaxis <- xlim + c(-1, 1) * diff(xlim) * 0.04 ncols <- if (is.null(d)) 1 else prod(d[-1]) if (is.null(col)) col <- rainbow_hcl(ncols, l = 50) if (is.null(pch)) pch <- c(19,15,17, 1:14, 16, 18, 20:25) labs <- if (is.null(d)) names(values) else dimnames(values)[[1]] if (is.null(xlab)) xlab <- if (is.null(d)) names(dimnames(x))[3] else names(dimnames(values))[1] if (is.null(ylab)) ylab <- paste(if (LOG) "L" else "", "OR(", paste(names(dimnames(x))[1:2], collapse = " / "), ")", sep = "") if (newpage) grid.newpage() if (transpose) { if (!add) { ## set up plot region, similar to plot.xy() pushViewport(plotViewport(xscale = ylimaxis, yscale = xlimaxis, default.units = "native", name = paste(prefix,"oddsratio_plot"))) grid.yaxis(name = "yaxis", seq_along(labs), labs, edits = gEdit("labels", rot = 90, hjust = .5, vjust = 0)) grid.xaxis() grid.text(ylab, y = unit(-3.5, "lines")) grid.text(xlab, x = unit(-3, "lines"), rot = 90) grid.text(main, y = unit(1, "npc") + unit(1, "lines"), gp = gp_main) pushViewport(viewport(xscale = ylimaxis, yscale = xlimaxis, default.units = "native", clip = "on")) ## baseline if (baseline) grid.lines(unit(c(1,1) - LOG, "native"), unit(c(0,1), "npc"), gp = gp_baseline) } # workhorse for one stratum draw_one_stratum <- function(vals, pch = "o", col = "black", offset = 0, jitter = 0) { if (bars) { if (any(vals > !LOG)) grid.rect(unit(vals[vals > !LOG], "native"), unit(seq_along(vals)[vals > !LOG], "native"), height = bar_width, width = unit(vals[vals > !LOG] - !LOG, "native"), just = "right", gp = gp_bars ) if (any(vals < !LOG)) grid.rect(unit(vals[vals < !LOG], "native"), unit(seq_along(vals)[vals < !LOG], "native"), height = bar_width, width = unit(abs(vals[vals < !LOG] - !LOG), "native"), just = "left", gp = gp_bars ) } if (lines) grid.lines(unit(vals, "native"), unit(seq_along(vals), "native"), gp = gpar(col = col, lwd = lwd_lines), default.units = "native" ) grid.points(unit(vals, "native"), unit(seq_along(vals), "native"), pch = pch, size = unit(cex, "char"), gp = gpar(col = col, lwd = lwd_lines), default.units = "native" ) if (confidence) for (i in seq_along(vals)) { ii <- i + jitter grid.lines(unit(c(lwr[offset + i], upr[offset + i]), "native"), unit(c(ii, ii), "native"), gp = gpar(col = col, lwd = lwd_confidence)) grid.lines(unit(c(lwr[offset + i], lwr[offset + i]), "native"), unit(c(ii - whiskers/2, ii + whiskers/2), "native"), gp = gpar(col = col, lwd = lwd_confidence)) grid.lines(unit(c(upr[offset + i], upr[offset + i]), "native"), unit(c(ii - whiskers/2, ii + whiskers/2), "native"), gp = gpar(col = col, lwd = lwd_confidence)) } } } else { if (!add) { ## set up plot region pushViewport(plotViewport(xscale = xlimaxis, yscale = ylimaxis, default.units = "native", name = "oddsratio_plot")) grid.xaxis(seq_along(labs), labs) grid.yaxis() grid.text(xlab, y = unit(-3.5, "lines")) grid.text(ylab, x = unit(-3, "lines"), rot = 90) grid.text(main, y = unit(1, "npc") + unit(1, "lines"), gp = gp_main) pushViewport(viewport(xscale = xlimaxis, yscale = ylimaxis, default.units = "native", clip = "on")) ## baseline if (baseline) grid.lines(unit(c(0,1), "npc"), unit(c(1,1) - LOG, "native"), gp = gp_baseline) } ## workhorse for one stratum draw_one_stratum <- function(vals, pch = "o", col = "black", offset = 0, jitter = 0) { if (bars) { if (any(vals > !LOG)) grid.rect(unit(seq_along(vals)[vals > !LOG], "native"), unit(vals[vals > !LOG], "native"), width = bar_width, height = unit(vals[vals > !LOG] - !LOG, "native"), just = "top", gp = gp_bars ) if (any(vals < !LOG)) grid.rect(unit(seq_along(vals)[vals < !LOG], "native"), unit(vals[vals < !LOG], "native"), width = bar_width, height = unit(abs(vals[vals < !LOG] - !LOG), "native"), just = "bottom", gp = gp_bars ) } if (lines) grid.lines(unit(seq_along(vals), "native"), unit(vals, "native"), gp = gpar(col = col, lwd = lwd_lines), default.units = "native" ) grid.points(unit(seq_along(vals), "native"), unit(vals, "native"), pch = pch, size = unit(cex, "char"), gp = gpar(col = col, lwd = lwd_lines), default.units = "native" ) if (confidence) for (i in seq_along(vals)) { ii <- i + jitter grid.lines(unit(c(ii, ii), "native"), unit(c(lwr[offset + i], upr[offset + i]), "native"), gp = gpar(col = col, lwd = lwd_confidence)) grid.lines(unit(c(ii - whiskers/2, ii + whiskers/2), "native"), unit(c(lwr[offset + i], lwr[offset + i]), "native"), gp = gpar(col = col, lwd = lwd_confidence)) grid.lines(unit(c(ii - whiskers/2, ii + whiskers/2), "native"), unit(c(upr[offset + i], upr[offset + i]), "native"), gp = gpar(col = col, lwd = lwd_confidence)) } } } if (is.null(d)) draw_one_stratum(values, pch[1], col[1]) else { jitt <- scale(seq_len(prod(d[-1])), scale = 25 * prod(d[-1])) for (i in 1 : prod(d[-1])) draw_one_stratum(values[(i - 1) * d[1] + seq(d[1])], pch[(i - 1 ) %% length(pch) + 1], col[i], offset = (i - 1) * d[1], jitt[i]) if (legend) grid_legend(legend_pos, labels = apply(expand.grid(dimnames(values)[-1]), 1, paste, collapse = "|"), pch = pch[1 : prod(d[-1])], col = col, lwd = legend_lwd, lty = "solid", size = legend_size, vgap = legend_vgap, gp = gp_legend, gp_frame = gp_legend_frame, inset = legend_inset, title = paste(names(dimnames(values)[-1]), collapse = " x "), gp_title = gp_legend_title, ...) } grid.rect(gp = gpar(fill = "transparent")) if (!add && pop) popViewport(2) if (return_grob) invisible(grid.grab()) else invisible(NULL) } lines.loddsratio <- function(x, legend = FALSE, confidence = FALSE, cex = 0, ...) { plot(x, add = TRUE, newpage = FALSE, legend = legend, confidence = confidence, cex = cex, ...) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/loddsratio.R
########################################################### ## mosaicplot mosaic <- function(x, ...) UseMethod("mosaic") mosaic.formula <- function(formula, data = NULL, highlighting = NULL, ..., main = NULL, sub = NULL, subset = NULL, na.action = NULL) { if (is.logical(main) && main) main <- deparse(substitute(data)) else if (is.logical(sub) && sub) sub <- deparse(substitute(data)) m <- match.call(expand.dots = FALSE) edata <- eval(m$data, parent.frame()) fstr <- strsplit(paste(deparse(formula), collapse = ""), "~") vars <- strsplit(strsplit(gsub(" ", "", fstr[[1]][2]), "\\|")[[1]], "\\+") varnames <- vars[[1]] condnames <- if (length(vars) > 1) vars[[2]] else NULL dep <- gsub(" ", "", fstr[[1]][1]) if (is.null(highlighting) && (!dep %in% c("","Freq"))) { if (all(varnames == ".")) { varnames <- if (is.data.frame(data)) colnames(data) else names(dimnames(as.table(data))) varnames <- varnames[-which(varnames %in% dep)] } varnames <- c(varnames, dep) highlighting <- length(varnames) + length(condnames) } if (inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) { condind <- NULL dat <- as.table(data) if(all(varnames != ".")) { ind <- match(varnames, names(dimnames(dat))) if (any(is.na(ind))) stop(paste("Can't find", paste(varnames[is.na(ind)], collapse=" / "), "in", deparse(substitute(data)))) if (!is.null(condnames)) { condind <- match(condnames, names(dimnames(dat))) if (any(is.na(condind))) stop(paste("Can't find", paste(condnames[is.na(condind)], collapse=" / "), "in", deparse(substitute(data)))) ind <- c(condind, ind) } dat <- margin.table(dat, ind) } mosaic.default(dat, main = main, sub = sub, highlighting = highlighting, condvars = if (is.null(condind)) NULL else match(condnames, names(dimnames(dat))), ...) } else { m <- m[c(1, match(c("formula", "data", "subset", "na.action"), names(m), 0))] m[[1]] <- as.name("xtabs") m$formula <- formula(paste(if("Freq" %in% colnames(data)) "Freq", "~", paste(c(condnames, varnames), collapse = "+"))) tab <- eval(m, parent.frame()) mosaic.default(tab, main = main, sub = sub, highlighting = highlighting, ...) } } mosaic.default <- function(x, condvars = NULL, split_vertical = NULL, direction = NULL, spacing = NULL, spacing_args = list(), gp = NULL, expected = NULL, shade = NULL, highlighting = NULL, highlighting_fill = rev(gray.colors(tail(dim(x), 1))), highlighting_direction = NULL, zero_size = 0.5, zero_split = FALSE, zero_shade = NULL, zero_gp = gpar(col = 0), panel = NULL, main = NULL, sub = NULL, ...) { zero_shade <- !is.null(shade) && shade || !is.null(expected) || !is.null(gp) if (!is.null(shade) && !shade) zero_shade = FALSE if (is.logical(main) && main) main <- deparse(substitute(x)) else if (is.logical(sub) && sub) sub <- deparse(substitute(x)) if (is.structable(x)) { if (is.null(direction) && is.null(split_vertical)) split_vertical <- attr(x, "split_vertical") x <- as.table(x) } if (is.null(split_vertical)) split_vertical <- FALSE d <- dim(x) dl <- length(d) ## splitting argument if (!is.null(direction)) split_vertical <- direction == "v" if (length(split_vertical) == 1) split_vertical <- rep(c(split_vertical, !split_vertical), length.out = dl) if (length(split_vertical) < dl) split_vertical <- rep(split_vertical, length.out = dl) ## highlighting if (!is.null(highlighting)) { if (is.character(highlighting)) highlighting <- match(highlighting, names(dimnames(x))) if (length(highlighting) > 0) { if (is.character(condvars)) condvars <- match(condvars, names(dimnames(x))) perm <- if (length(condvars) > 0) c(condvars, seq(dl)[-c(condvars,highlighting)], highlighting) else c(seq(dl)[-highlighting], highlighting) x <- aperm(x, perm) d <- d[perm] split_vertical <- split_vertical[perm] if (is.null(spacing)) spacing <- spacing_highlighting if (is.function(highlighting_fill)) highlighting_fill <- highlighting_fill(d[dl]) if (is.null(gp)) gp <- gpar(fill = aperm(array(highlighting_fill, dim = rev(d)))) if (!is.null(highlighting_direction)) { split_vertical[dl] <- highlighting_direction %in% c("left", "right") if (highlighting_direction %in% c("left", "top")) { ## ugly: tmp <- as.data.frame.table(x) tmp[,dl] <- factor(tmp[,dl], rev(levels(tmp[,dl]))) x <- xtabs(Freq ~ ., data = tmp) gp <- gpar(fill = aperm(array(rev(highlighting_fill), dim = rev(d)))) } } } } else if (!is.null(condvars)) { # Conditioning only if (is.character(condvars)) condvars <- match(condvars, names(dimnames(x))) if (length(condvars) > 0) { perm <- c(condvars, seq(dl)[-condvars]) x <- aperm(x, perm) split_vertical <- split_vertical[perm] } if (is.null(spacing)) spacing <- spacing_conditional } ## spacing argument if (is.null(spacing)) spacing <- if (dl < 3) spacing_equal else spacing_increase strucplot(x, condvars = if (is.null(condvars)) NULL else length(condvars), core = struc_mosaic(zero_size = zero_size, zero_split = zero_split, zero_shade = zero_shade, zero_gp = zero_gp, panel = panel), split_vertical = split_vertical, spacing = spacing, spacing_args = spacing_args, gp = gp, expected = expected, shade = shade, main = main, sub = sub, ...) } ## old code: more elegant, but less performant ## ## struc_mosaic2 <- function(zero_size = 0.5, zero_split = FALSE, ## zero_shade = TRUE, zero_gp = gpar(col = 0)) ## function(residuals, observed, expected = NULL, spacing, gp, split_vertical, prefix = "") { ## dn <- dimnames(observed) ## dnn <- names(dn) ## dx <- dim(observed) ## dl <- length(dx) ## ## split workhorse ## zerostack <- character(0) ## split <- function(x, i, name, row, col, zero) { ## cotab <- co_table(x, 1) ## margin <- sapply(cotab, sum) ## v <- split_vertical[i] ## d <- dx[i] ## ## compute total cols/rows and build split layout ## dist <- unit.c(unit(margin, "null"), spacing[[i]]) ## idx <- matrix(1:(2 * d), nrow = 2, byrow = TRUE)[-2 * d] ## layout <- if (v) ## grid.layout(ncol = 2 * d - 1, widths = dist[idx]) ## else ## grid.layout(nrow = 2 * d - 1, heights = dist[idx]) ## vproot <- viewport(layout.pos.col = col, layout.pos.row = row, ## layout = layout, name = remove_trailing_comma(name)) ## ## next level: either create further splits, or final viewports ## name <- paste(name, dnn[i], "=", dn[[i]], ",", sep = "") ## row <- col <- rep.int(1, d) ## if (v) col <- 2 * 1:d - 1 else row <- 2 * 1:d - 1 ## f <- if (i < dl) ## function(m) { ## co <- cotab[[m]] ## z <- mean(co) <= .Machine$double.eps ## if (z && !zero && !zero_split) zerostack <<- c(zerostack, name[m]) ## split(co, i + 1, name[m], row[m], col[m], z && !zero_split) ## } ## else ## function(m) { ## if (cotab[[m]] <= .Machine$double.eps && !zero) ## zerostack <<- c(zerostack, name[m]) ## viewport(layout.pos.col = col[m], layout.pos.row = row[m], ## name = remove_trailing_comma(name[m])) ## } ## vpleaves <- structure(lapply(1:d, f), class = c("vpList", "viewport")) ## vpTree(vproot, vpleaves) ## } ## ## start spltting on top, creates viewport-tree ## pushViewport(split(observed + .Machine$double.eps, ## i = 1, name = paste(prefix, "cell:", sep = ""), ## row = 1, col = 1, zero = FALSE)) ## ## draw rectangles ## mnames <- apply(expand.grid(dn), 1, ## function(i) paste(dnn, i, collapse=",", sep = "=") ## ) ## zeros <- observed <= .Machine$double.eps ## ## draw zero cell lines ## for (i in remove_trailing_comma(zerostack)) { ## seekViewport(i) ## grid.lines(x = 0.5) ## grid.lines(y = 0.5) ## if (!zero_shade && zero_size > 0) { ## grid.points(0.5, 0.5, pch = 19, size = unit(zero_size, "char"), ## gp = zero_gp, ## name = paste(prefix, "disc:", mnames[i], sep = "")) ## grid.points(0.5, 0.5, pch = 1, size = unit(zero_size, "char"), ## name = paste(prefix, "circle:", mnames[i], sep = "")) ## } ## } ## # draw boxes ## for (i in seq_along(mnames)) { ## seekViewport(paste(prefix, "cell:", mnames[i], sep = "")) ## gpobj <- structure(lapply(gp, function(x) x[i]), class = "gpar") ## if (!zeros[i]) { ## grid.rect(gp = gpobj, name = paste(prefix, "rect:", mnames[i], sep = "")) ## } else { ## if (zero_shade && zero_size > 0) { ## grid.points(0.5, 0.5, pch = 19, size = unit(zero_size, "char"), ## gp = gpar(col = gp$fill[i]), ## name = paste(prefix, "disc:", mnames[i], sep = "")) ## grid.points(0.5, 0.5, pch = 1, size = unit(zero_size, "char"), ## name = paste(prefix, "circle:", mnames[i], sep = "")) ## } ## } ## } ## } ## class(struc_mosaic2) <- "grapcon_generator" struc_mosaic <- function(zero_size = 0.5, zero_split = FALSE, zero_shade = TRUE, zero_gp = gpar(col = 0), panel = NULL) function(residuals, observed, expected = NULL, spacing, gp, split_vertical, prefix = "") { dn <- dimnames(observed) dnn <- names(dn) dx <- dim(observed) dl <- length(dx) zeros <- function(gp, name) { grid.lines(x = 0.5) grid.lines(y = 0.5) if (zero_size > 0) { grid.points(0.5, 0.5, pch = 19, size = unit(zero_size, "char"), gp = gp, name = paste(prefix, "disc:", name, sep = "")) grid.points(0.5, 0.5, pch = 1, size = unit(zero_size, "char"), name = paste(prefix, "circle:", name, sep = "")) } } ## split workhorse zerostack <- character(0) split <- function(x, i, name, row, col, zero, index) { cotab <- co_table(x, 1) margin <- sapply(cotab, sum) margin[margin == 0] <- .Machine$double.eps # margin <- margin + .Machine$double.eps v <- split_vertical[i] d <- dx[i] ## compute total cols/rows and build split layout dist <- if (d > 1) unit.c(unit(margin, "null"), spacing[[i]]) else unit(margin, "null") idx <- matrix(1:(2 * d), nrow = 2, byrow = TRUE)[-2 * d] layout <- if (v) grid.layout(ncol = 2 * d - 1, widths = dist[idx]) else grid.layout(nrow = 2 * d - 1, heights = dist[idx]) pushViewport(viewport(layout.pos.col = col, layout.pos.row = row, layout = layout, name = paste(prefix, "cell:", remove_trailing_comma(name), sep = ""))) ## next level: either create further splits, or final viewports row <- col <- rep.int(1, d) if (v) col <- 2 * 1:d - 1 else row <- 2 * 1:d - 1 for (m in 1:d) { nametmp <- paste(name, dnn[i], "=", dn[[i]][m], ",", sep = "") if (i < dl) { co <- cotab[[m]] ## zeros z <- mean(co) <= .Machine$double.eps split(co, i + 1, nametmp, row[m], col[m], z && !zero_split, cbind(index, m)) if (z && !zero && !zero_split && !zero_shade && (zero_size > 0)) zeros(zero_gp, nametmp) } else { pushViewport(viewport(layout.pos.col = col[m], layout.pos.row = row[m], name = paste(prefix, "cell:", remove_trailing_comma(nametmp), sep = ""))) ## zeros if (cotab[[m]] <= .Machine$double.eps && !zero) { zeros(if (!zero_shade) zero_gp else gpar(col = gp$fill[cbind(index,m)]), nametmp) } else { ## rectangles gpobj <- structure(lapply(gp, function(x) x[cbind(index, m)]), class = "gpar") nam <- paste(prefix, "rect:", remove_trailing_comma(nametmp), sep = "") if (!is.null(panel)) panel(residuals, observed, expected, c(cbind(index, m)), gpobj, nam) else grid.rect(gp = gpobj, name = nam) } } upViewport(1) } } ## start splitting on top, creates viewport-tree split(observed, i = 1, name = "", row = 1, col = 1, zero = FALSE, index = cbind()) } class(struc_mosaic) <- "grapcon_generator"
/scratch/gouwar.j/cran-all/cranData/vcd/R/mosaic.R
mplot <- function(..., .list = list(), layout = NULL, cex = NULL, main = NULL, gp_main = gpar(fontsize = 20), sub = NULL, gp_sub = gpar(fontsize = 15), keep_aspect_ratio = TRUE) { l <- c(list(...), .list) ll <- length(l) m <- !is.null(main) s <- !is.null(sub) ## calculate layout if (is.null(layout)) layout <- c(trunc(sqrt(ll)), ceiling(ll / trunc(sqrt(ll)))) ## push base layout grid.newpage() hts = unit(1 - 0.1 * m - 0.1 * s, "null") if (m) hts <- c(unit(0.1, "null"), hts) if (s) hts <- c(hts, unit(0.1, "null")) pushViewport(viewport(layout = grid.layout(nrow = 1 + m + s, ncol = 1, heights = hts) ) ) ## push main, if any if (!is.null(main)) { pushViewport(viewport(layout.pos.row = 1, layout.pos.col = NULL)) grid.text(main, gp = gp_main) popViewport(1) } ## push strucplots if (is.null(cex)) cex <- sqrt(1/layout[1]) pushViewport(viewport(layout.pos.row = 1 + m, layout.pos.col = NULL)) pushViewport(viewport(layout = grid.layout(nrow = layout[1], ncol = layout[2]), gp = gpar(cex = cex) ) ) count <- 1 for (i in seq_len(layout[1])) for (j in seq_len(layout[2])) if(count <= ll) { pushViewport(viewport(layout.pos.row = i, layout.pos.col = j)) pushViewport(viewport(width = 1, height = 1, default.units = if (keep_aspect_ratio) "snpc" else "npc")) if (inherits(l[[count]], "grob")) grid.draw(l[[count]]) else if (!is.null(attr(l[[count]], "grob"))) grid.draw(attr(l[[count]], "grob")) popViewport(2) count <- count + 1 } popViewport(2) ## push sub, if any if (!is.null(sub)) { pushViewport(viewport(layout.pos.row = 1 + m + s, layout.pos.col = NULL)) grid.text(sub, gp = gp_sub) popViewport() } popViewport(1) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/mplot.R
"oddsratio" <- function(x, stratum = NULL, log = TRUE) loddsratio(x, strata = stratum, log = log) ## "oddsratio" <- ## function (x, stratum = NULL, log = TRUE) { ## l <- length(dim(x)) ## if (l > 2 && is.null(stratum)) ## stratum <- 3:l ## if (l - length(stratum) > 2) ## stop("All but 2 dimensions must be specified as strata.") ## if (l == 2 && dim(x) != c(2, 2)) ## stop("Not a 2x2 table.") ## if (!is.null(stratum) && dim(x)[-stratum] != c(2,2)) ## stop("Need strata of 2x2 tables.") ## lor <- function (y) { ## if (any(y == 0)) ## y <- y + 0.5 ## y <- log(y) ## or <- y[1,1] + y[2,2] - y[1,2] - y[2,1] ## if (log) or else exp(or) ## } ## ase <- function(y) { ## if (any(y == 0)) ## y <- y + 0.5 ## sqrt(sum(1/y)) ## } ## if(is.null(stratum)) { ## LOR <- lor(x) ## ASE <- ase(x) ## } else { ## LOR <- apply(x, stratum, lor) ## ASE <- apply(x, stratum, ase) ## } ## structure(LOR, ## ASE = ASE, ## log = log, ## class = "oddsratio" ## )} ## "print.oddsratio" <- ## function(x, ...) { ## if (length(dim(x)) > 1) ## print(cbind(unclass(x)), ...) ## else ## print(c(x), ...) ## invisible(x) ## } ## "summary.oddsratio" <- ## function(object, ...) { ## if(!is.null(dim(object))) ## ret <- object ## else { ## LOG <- attr(object, "log") ## ASE <- attr(object, "ASE") ## Z <- object / ASE ## ret <- cbind("Estimate" = object, ## "Std. Error" = if (LOG) ASE, ## "z value" = if (LOG) Z, ## "Pr(>|z|)" = if (LOG) 2 * pnorm(-abs(Z)) ## ) ## colnames(ret)[1] <- if (LOG) "Log Odds Ratio" else "Odds Ratio" ## } ## class(ret) <- "summary.oddsratio" ## ret ## } ## "print.summary.oddsratio" <- ## function(x, ...) { ## if(!is.null(attr(x, "log"))) { ## cat("\n") ## cat(if(attr(x, "log")) "Log Odds Ratio(s):" else "Odds Ratio(s):", "\n\n") ## print(as.data.frame(unclass(x)), ...) ## cat("\nAsymptotic Standard Error(s):\n\n") ## print(attr(x, "ASE"), ...) ## cat("\n") ## } else printCoefmat(unclass(x), ...) ## invisible(x) ## } ## "plot.oddsratio" <- ## function(x, ## conf_level = 0.95, ## type = "o", ## xlab = NULL, ## ylab = NULL, ## xlim = NULL, ## ylim = NULL, ## whiskers = 0.1, ## baseline = TRUE, ## transpose = FALSE, ## ...) ## { ## if (length(dim(x)) > 1) ## stop ("Plot function works only on vectors.") ## LOG <- attr(x, "log") ## confidence <- !(is.null(conf_level) || conf_level == FALSE) ## oddsrange <- range(x) ## if(confidence) { ## CI <- confint(x, level = conf_level) ## lwr <- CI[,1] ## upr <- CI[,2] ## oddsrange[1] <- trunc(min(oddsrange[1], min(lwr))) ## oddsrange[2] <- ceiling(max(oddsrange[2], max(upr))) ## } ## if (transpose) { ## plot(x = unclass(x), ## y = 1:length(x), ## ylab = if (!is.null(ylab)) ylab else "Strata", ## xlab = if (!is.null(xlab)) xlab else if (LOG) "Log Odds Ratio" else "Odds Ratio", ## type = type, ## yaxt = "n", ## xlim = if(is.null(xlim)) oddsrange else xlim, ## ...) ## axis (2, at = 1:length(x), names(x)) ## if (baseline) ## lines(c(1,1) - LOG, c(0,length(x) + 1), lty = 2, col = "red") ## if (confidence) ## for (i in 1:length(x)) { ## lines(c(lwr[i], upr[i]), c(i, i)) ## lines(c(lwr[i], lwr[i]), c(i - whiskers/2, i + whiskers/2)) ## lines(c(upr[i], upr[i]), c(i - whiskers/2, i + whiskers/2)) ## } ## } else { ## plot(unclass(x), ## xlab = if (!is.null(xlab)) xlab else "Strata", ## ylab = if(!is.null(ylab)) ylab else if(LOG) "Log Odds Ratio" else "Odds Ratio", ## type = type, ## xaxt = "n", ## ylim = if(is.null(ylim)) oddsrange else ylim, ## ...) ## axis (1, at = 1:length(x), names(x)) ## if (baseline) ## lines(c(0,length(x) + 1), c(1,1) - LOG, lty = 2, col = "red") ## if (confidence) ## for (i in 1:length(x)) { ## lines(c(i, i), c(lwr[i], upr[i])) ## lines(c(i - whiskers/2, i + whiskers/2), c(lwr[i], lwr[i])) ## lines(c(i - whiskers/2, i + whiskers/2), c(upr[i], upr[i])) ## } ## } ## } ## "confint.oddsratio" <- ## function(object, parm, level = 0.95, ...) { ## ASE <- attr(object, "ASE") ## LOG <- attr(object, "log") ## I <- ASE * qnorm((1 + level) / 2) ## cbind( ## lwr = if (LOG) object - I else exp(log(object) - I), ## upr = if (LOG) object + I else exp(log(object) + I) ## ) ## }
/scratch/gouwar.j/cran-all/cranData/vcd/R/oddsratioplot.R
################################################################# ### pairsplot ## modified, 2-14-2014, MF: fix expected values for type= pairs.table <- function(x, upper_panel = pairs_mosaic, upper_panel_args = list(), lower_panel = pairs_mosaic, lower_panel_args = list(), diag_panel = pairs_diagonal_mosaic, diag_panel_args = list(), main = NULL, sub = NULL, main_gp = gpar(fontsize = 20), sub_gp = gpar(fontsize = 15), space = 0.3, newpage = TRUE, pop = TRUE, return_grob = FALSE, margins = unit(1, "lines"), ...) { if (newpage) grid.newpage() if (inherits(upper_panel, "grapcon_generator")) upper_panel <- do.call("upper_panel", c(upper_panel_args, list(...))) if (inherits(lower_panel, "grapcon_generator")) lower_panel <- do.call("lower_panel", c(lower_panel_args, list(...))) if (inherits(diag_panel, "grapcon_generator")) diag_panel <- do.call("diag_panel", diag_panel_args) d <- length(dim(x)) l <- grid.layout(d, d) pushViewport(viewport(width = unit(1, "snpc"), height = unit(1, "snpc"))) pushViewport(vcdViewport(mar = margins, legend = FALSE, legend_width = NULL, main = !is.null(main), sub = !is.null(sub))) ## titles if (!is.null(main)) { seekViewport("main") if (is.logical(main) && main) main <- deparse(substitute(x)) grid.text(main, gp = main_gp) } if (!is.null(sub)) { seekViewport("sub") if (is.logical(sub) && sub && is.null(main)) sub <- deparse(substitute(x)) grid.text(sub, gp = sub_gp) } seekViewport("plot") pushViewport(viewport(layout = l, y = 0, just = "bottom")) for (i in 1:d) for(j in 1:d) { pushViewport(viewport(layout.pos.col = i, layout.pos.row = j)) pushViewport(viewport(width = 1 - space, height = 1 - space)) if (i > j) { if (!is.null(upper_panel)) upper_panel(x, j, i) } else if (i < j) { if (!is.null(lower_panel)) lower_panel(x, j, i) } else if (!is.null(diag_panel)) diag_panel(x, i) if (pop) popViewport(2) else upViewport(2) } if (pop) popViewport(3) else upViewport(3) if (return_grob) invisible(structure(x, grob = grid.grab())) else invisible(x) } pairs.structable <- function(x, ...) pairs(as.table(x), ...) ## upper/lower panels pairs_assoc <- function(...) pairs_strucplot(panel = assoc, ...) class(pairs_assoc) <- "grapcon_generator" pairs_mosaic <- function(...) pairs_strucplot(panel = mosaic, ...) class(pairs_mosaic) <- "grapcon_generator" pairs_sieve <- function(...) pairs_strucplot(panel = sieve, ...) class(pairs_sieve) <- "grapcon_generator" pairs_strucplot <- function(panel = mosaic, type = c("pairwise", "total", "conditional", "joint"), legend = FALSE, margins = c(0, 0, 0, 0), labeling = NULL, ...) { type = match.arg(type) function(x, i, j) { index <- 1:length(dim(x)) rest <- index[!index %in% c(i, j)] rest2 <- index[!index %in% 1:2] tl <- tail(index, 2) rest3 <- index[!index %in% tl] expected <- switch(type, joint = list(1:2, rest2), conditional = list(c(tl[1], rest3), c(tl[2], rest3)), total = sapply(c(j, i, rest), list), NULL) margin <- switch(type, pairwise = c(j, i), conditional = c(rest, j, i), c(j, i, rest)) panel(x = margin.table(x, margin), expected = expected, labeling = labeling, margins = margins, legend = legend, split_vertical = TRUE, newpage = FALSE, pop = FALSE, prefix = paste("panel:Y=",names(dimnames(x))[i],",X=", names(dimnames(x))[j],"|",sep = ""), ...) } } class(pairs_strucplot) <- "grapcon_generator" ## diagonal panels pairs_text <- function(dimnames = TRUE, gp_vartext = gpar(fontsize = 17), gp_leveltext = gpar(), gp_border = gpar(), ...) function(x, i) { x <- margin.table(x, i) grid.rect(gp = gp_border) grid.text(names(dimnames(x)), gp = gp_vartext, y = 0.5 + dimnames * 0.05, ...) if (dimnames) grid.text(paste("(",paste(names(x), collapse = ","), ")", sep = ""), y = 0.4, gp = gp_leveltext) } class(pairs_text) <- "grapcon_generator" pairs_diagonal_text <- function(varnames = TRUE, gp_vartext = gpar(fontsize = 17, fontface = "bold"), gp_leveltext = gpar(), gp_border = gpar(), pos = c("right","top"), distribute = c("equal","margin"), rot = 0, ...) { xc <- unit(switch(pos[1], left = 0.1, center = 0.5, 0.9), "npc") yc <- unit(switch(pos[2], top = 0.9, center = 0.5, 0.1), "npc") distribute <- match.arg(distribute) function(x, i) { x <- margin.table(x, i) grid.rect(gp = gp_border) if (varnames) grid.text(names(dimnames(x)), gp = gp_vartext, x = xc, y = yc, just = pos, ...) l <- length(dimnames(x)[[1]]) po <- if (distribute == "equal") unit(cumsum(rep(1 / (l + 1), l)), "npc") else { sizes = prop.table(x) unit(cumsum(c(0,sizes))[1:l] + sizes / 2, "npc") } grid.text(dimnames(x)[[1]], x = po, y = unit(1, "npc") - po, gp = gp_leveltext, rot = rot) } } class(pairs_diagonal_text) <- "grapcon_generator" pairs_barplot <- function(gp_bars = NULL, gp_vartext = gpar(fontsize = 17), gp_leveltext = gpar(), gp_axis = gpar(), just_leveltext = c("center", "bottom"), just_vartext = c("center", "top"), rot = 0, abbreviate = FALSE, check_overlap = TRUE, fill = "grey", var_offset = unit(1, "npc"), ...) function(x, i) { if (!is.unit(var_offset)) var_offset <- unit(var_offset, "npc") dn <- names(dimnames(x)) x <- margin.table(x, i) if (is.function(fill)) fill <- rev(fill(dim(x))) if (is.null(gp_bars)) gp_bars <- gpar(fill = fill) pushViewport(viewport(x = 0.3, y = 0.1, width = 0.7, height = 0.7, yscale = c(0,max(x)), just = c("left", "bottom")) ) xpos <- seq(0, 1, length.out = length(x) + 1)[-1] halfstep <- (xpos[2] - xpos[1]) / 2 grid.rect(xpos - halfstep, rep.int(0, length(x)), height = x, just = c("center", "bottom"), width = halfstep, gp = gp_bars, default.units = "native", name = paste("panel:diag=", dn[i], "|bars", sep = ""), ...) grid.yaxis(at = pretty(c(0,max(x))), gp = gp_axis) txt <- names(x) if (abbreviate) txt <- abbreviate(txt, abbreviate) grid.text(txt, y = unit(-0.15, "npc"), rot = rot, x = xpos - halfstep, just = just_leveltext, gp = gp_leveltext, check.overlap = check_overlap) popViewport(1) grid.text(names(dimnames(x)), y = var_offset, just = just_vartext, gp = gp_vartext) } class(pairs_barplot) <- "grapcon_generator" pairs_diagonal_mosaic <- function(split_vertical = TRUE, margins = unit(0, "lines"), offset_labels = -0.4, offset_varnames = 0, gp = NULL, fill = "grey", labeling = labeling_values, alternate_labels = TRUE, ...) function(x, i) { if (is.function(fill)) fill <- rev(fill(dim(x)[i])) if (is.null(gp)) gp <- gpar(fill = fill) mosaic(margin.table(x, i), newpage = FALSE, split_vertical = split_vertical, margins = margins, offset_labels = offset_labels, offset_varnames = offset_varnames, prefix = "diag", gp = gp, labeling = labeling_values, labeling_args = list(alternate_labels = TRUE), ...) } class(pairs_diagonal_mosaic) <- "grapcon_generator"
/scratch/gouwar.j/cran-all/cranData/vcd/R/pairsplot.R
plot.loglm <- function(x, panel = mosaic, type = c("observed", "expected"), residuals_type = c("pearson", "deviance"), gp = shading_hcl, gp_args = list(), ...) { residuals_type <- match.arg(tolower(residuals_type), c("pearson", "deviance")) if(is.null(x$fitted)) x <- update(x, fitted = TRUE) expected <- fitted(x) residuals <- residuals(x, type = "pearson") observed <- residuals * sqrt(expected) + expected if(residuals_type == "deviance") residuals <- residuals(x, type = "deviance") gp <- if(inherits(gp, "grapcon_generator")) do.call("gp", c(list(observed, residuals, expected, x$df), as.list(gp_args))) else gp panel(observed, residuals = residuals, expected = expected, type = type, residuals_type = residuals_type, gp = gp, ...) } mosaic.loglm <- function(x, ...) { plot(x, panel = mosaic, ...) } assoc.loglm <- function(x, ...) { plot(x, panel = assoc, ...) } sieve.loglm <- function(x, ...) { plot(x, panel = sieve, ...) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/plot.loglm.R
rootogram <- function(x, ...) { UseMethod("rootogram") } rootogram.goodfit <- function(x, ...) { rootogram.default(x$observed, x$fitted, names = x$count, df = x$df, ...) } rootogram.default <- function(x, fitted, names = NULL, scale = c("sqrt", "raw"), type = c("hanging", "standing", "deviation"), shade = FALSE, legend = TRUE, legend_args = list(x = 0, y = 0.2, height = 0.6), df = NULL, rect_gp = NULL, rect_gp_args = list(), lines_gp = gpar(col = "red", lwd = 2), points_gp = gpar(col = "red"), pch = 19, xlab = NULL, ylab = NULL, ylim = NULL, main = NULL, sub = NULL, margins = unit(0, "lines"), title_margins = NULL, legend_width = NULL, main_gp = gpar(fontsize = 20), sub_gp = gpar(fontsize = 15), name = "rootogram", prefix = "", keep_aspect_ratio = FALSE, newpage = TRUE, pop = TRUE, return_grob = FALSE, ...) { if(is.null(names)) names <- names(x) if(is.table(x)) { if(length(dim(x)) > 1) stop ("x must be a 1-way table") x <- as.vector(x) } obs <- x fit <- fitted res <- (obs - fit) / sqrt(fit) if(is.null(xlab)) {xlab <- "Number of Occurrences"} if(match.arg(scale) == "sqrt") { obs <- sqrt(obs) fit <- sqrt(fit) if(is.null(ylab)) {ylab <- "sqrt(Frequency)"} } else { if(is.null(ylab)) {ylab <- "Frequency"} } ## rect_gp (color, fill, lty, etc.) argument if (shade) { if (is.null(rect_gp)) rect_gp <- shading_hcl if (is.function(rect_gp)) { if (is.null(legend) || (is.logical(legend) && legend)) legend <- legend_resbased gpfun <- if (inherits(rect_gp, "grapcon_generator")) do.call("rect_gp", c(list(obs, res, fit, df), rect_gp_args)) else rect_gp rect_gp <- gpfun(res) } else if (!is.null(legend) && !(is.logical(legend) && !legend)) stop("rect_gp argument must be a shading function for drawing a legend") } if (is.null(rect_gp)) rect_gp <- gpar(fill = "lightgray") ## set up page if (newpage) grid.newpage() if (keep_aspect_ratio) pushViewport(viewport(width = 1, height = 1, default.units = "snpc")) pushViewport(vcdViewport(mar = margins, oma = title_margins, legend = shade && !(is.null(legend) || is.logical(legend) && !legend), main = !is.null(main), sub = !is.null(sub), keep_aspect_ratio = keep_aspect_ratio, legend_width = legend_width, prefix = prefix)) ## legend if (inherits(legend, "grapcon_generator")) legend <- do.call("legend", legend_args) if (shade && !is.null(legend) && !(is.logical(legend) && !legend)) { seekViewport(paste(prefix, "legend", sep = "")) legend(res, gpfun, "Pearson\nresiduals:") } ## titles if (!is.null(main)) { seekViewport(paste(prefix, "main", sep = "")) if (is.logical(main) && main) main <- deparse(substitute(x)) grid.text(main, gp = main_gp) } if (!is.null(sub)) { seekViewport(paste(prefix, "sub", sep = "")) if (is.logical(sub) && sub && is.null(main)) sub <- deparse(substitute(x)) grid.text(sub, gp = sub_gp) } seekViewport(paste(prefix, "plot", sep = "")) switch(match.arg(type), "hanging" = { if(is.null(ylim)) {ylim <- range(-0.1 * c(fit-obs,fit), c(fit-obs,fit)) + c(0, 0.1)} dummy <- grid_barplot(obs, names = names, offset = fit - obs, gp = rect_gp, xlab = xlab, ylab = ylab, ylim = ylim, name = name, newpage = FALSE, pop = FALSE, return_grob = FALSE, ...) downViewport(name) grid.lines(x = dummy, y = fit, default.units = "native", gp = lines_gp) grid.points(x = dummy, y = fit, default.units = "native", gp = points_gp, pch = pch) grid.lines(x = unit(c(0, 1), "npc"), y = unit(0, "native")) if(pop) popViewport() else upViewport() }, "standing" = { if(is.null(ylim)) {ylim <- range(-0.01 * c(obs,fit), c(obs,fit)) } dummy <- grid_barplot(obs, names = names, gp = rect_gp, xlab = xlab, ylab = ylab, ylim = ylim, name = name, newpage = FALSE, pop = FALSE, return_grob = FALSE, ...) downViewport(name) grid.lines(x = dummy, y = fit, default.units = "native", gp = lines_gp) grid.points(x = dummy, y = fit, default.units = "native", gp = points_gp, pch = pch) if(pop) popViewport() else upViewport() }, "deviation" = { if(is.null(ylim)) {ylim <- range(-0.1 * c(fit-obs,fit), c(fit-obs,fit)) + c(0, 0.1)} dummy <- grid_barplot(fit - obs, names = names, gp = rect_gp, xlab = xlab, ylab = ylab, ylim = ylim, name = name, newpage = FALSE, pop = FALSE, return_grob = FALSE, ...) downViewport(name) grid.lines(x = dummy, y = fit, default.units = "native", gp = lines_gp) grid.points(x = dummy, y = fit, default.units = "native", gp = points_gp, pch = pch) if(pop) popViewport() else upViewport() } ) if (return_grob) invisible(grid.grab()) else invisible(NULL) } grid_barplot <- function(height, width = 0.8, offset = 0, names = NULL, xlim = NULL, ylim = NULL, xlab = "", ylab = "", main = "", gp = gpar(fill = "lightgray"), name = "grid_barplot", newpage = TRUE, pop = FALSE, return_grob = FALSE) { if(is.null(names)) names <- names(height) height <- as.vector(height) n <- length(height) width <- rep(width, length.out = n) offset <- rep(offset, length.out = n) if(is.null(names)) names <- rep("", n) if(is.null(xlim)) xlim <- c(1 - mean(width[c(1, n)]), n + mean(width[c(1, n)])) if(is.null(ylim)) ylim <- c(min(offset), max(height + offset)) if(newpage) grid.newpage() pushViewport(plotViewport(xscale = xlim, yscale = ylim, default.units = "native", name = name)) grid.rect(x = 1:n, y = offset, width = width, height = height, just = c("centre", "bottom"), default.units = "native", gp = gp) grid.yaxis() grid.text(names, x = unit(1:n, "native"), y = unit(rep(-1.5, n), "lines")) grid.text(xlab, y = unit(-3.5, "lines")) grid.text(ylab, x = unit(-3, "lines"), rot = 90) grid.text(main, y = unit(1, "npc") + unit(2, "lines"), gp = gpar(fontface = "bold")) if(pop) popViewport() else upViewport() if (return_grob) invisible(structure(1:n, grob = grid.grab())) else invisible(1:n) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/rootogram.R
## convenience function for interfacing ## HCL colors as implemented in colorspace hcl2hex <- function(h = 0, c = 35, l = 85, fixup = TRUE) { colorspace::hex(polarLUV(l, c, h), fixup = fixup) } ## shading-generating functions should take at least the arguments ## observed, residuals, expected, df ## and return a function which takes a single argument (interpreted ## to be a vector of residuals). shading_hsv <- function(observed, residuals = NULL, expected = NULL, df = NULL, h = c(2/3, 0), s = c(1, 0), v = c(1, 0.5), interpolate = c(2, 4), lty = 1, eps = NULL, line_col = "black", p.value = NULL, level = 0.95, ...) { ## get h/s/v and lty my.h <- rep(h, length.out = 2) ## positive and negative hue my.s <- rep(s, length.out = 2) ## maximum and minimum saturation my.v <- rep(v, length.out = 2) ## significant and non-significant value lty <- rep(lty, length.out = 2) ## positive and negative lty ## model fitting (if necessary) if(is.null(expected) && !is.null(residuals)) stop("residuals without expected values specified") if(!is.null(expected) && is.null(df) && is.null(p.value)) { warning("no default inference available without degrees of freedom") p.value <- NA } if(is.null(expected) && !is.null(observed)) { expected <- loglin(observed, 1:length(dim(observed)), fit = TRUE, print = FALSE) df <- expected$df expected <- expected$fit } if(is.null(residuals) && !is.null(observed)) residuals <- (observed - expected)/sqrt(expected) ## conduct significance test (if specified) if(is.null(p.value)) p.value <- function(observed, residuals, expected, df) pchisq(sum(as.vector(residuals)^2), df, lower.tail = FALSE) if(!is.function(p.value) && is.na(p.value)) { v <- my.v[1] p.value <- NULL } else { if(is.function(p.value)) p.value <- p.value(observed, residuals, expected, df) v <- if(p.value < (1-level)) my.v[1] else my.v[2] } ## set up function for interpolation of saturation if(!is.function(interpolate)) { col.bins <- sort(interpolate) interpolate <- stepfun(col.bins, seq(my.s[2], my.s[1], length.out = length(col.bins) + 1)) col.bins <- sort(unique(c(col.bins, 0, -col.bins))) } else { col.bins <- NULL } ## store color and lty information for legend legend <- NULL if(!is.null(col.bins)) { res2 <- col.bins res2 <- c(head(res2, 1) - 1, res2[-1] - diff(res2)/2, tail(res2, 1) + 1) legend.col <- hsv(ifelse(res2 > 0, my.h[1], my.h[2]), pmax(pmin(interpolate(abs(res2)), 1), 0), v, ...) lty.bins <- 0 legend.lty <- lty[2:1] legend <- list(col = legend.col, col.bins = col.bins, lty = legend.lty, lty.bins = lty.bins) } ## set up function that computes color/lty from residuals rval <- function(x) { res <- as.vector(x) fill <- hsv(ifelse(res > 0, my.h[1], my.h[2]), pmax(pmin(interpolate(abs(res)), 1), 0), v, ...) dim(fill) <- dim(x) col <- rep(line_col, length.out = length(res)) if(!is.null(eps)) { eps <- abs(eps) col[res > eps] <- hsv(my.h[1], 1, v, ...) col[res < -eps] <- hsv(my.h[2], 1, v, ...) } dim(col) <- dim(x) # line type should be solid if abs(resid) < eps ltytmp <- ifelse(x > 0, lty[1], lty[2]) if(!is.null(eps)) ltytmp[abs(x) < abs(eps)] <- lty[1] dim(ltytmp) <- dim(x) return(structure(list(col = col, fill = fill, lty = ltytmp), class = "gpar")) } attr(rval, "legend") <- legend attr(rval, "p.value") <- p.value return(rval) } class(shading_hsv) <- "grapcon_generator" shading_hcl <- function(observed, residuals = NULL, expected = NULL, df = NULL, h = NULL, c = NULL, l = NULL, interpolate = c(2, 4), lty = 1, eps = NULL, line_col = "black", p.value = NULL, level = 0.95, ...) { ## set defaults if(is.null(h)) h <- c(260, 0) if(is.null(c)) c <- c(100, 20) if(is.null(l)) l <- c(90, 50) ## get h/c/l and lty my.h <- rep(h, length.out = 2) ## positive and negative hue my.c <- rep(c, length.out = 2) ## significant and non-significant maximum chroma my.l <- rep(l, length.out = 2) ## maximum and minimum luminance lty <- rep(lty, length.out = 2) ## positive and negative lty ## model fitting (if necessary) if(is.null(expected) && !is.null(residuals)) stop("residuals without expected values specified") if(!is.null(expected) && is.null(df) && is.null(p.value)) { warning("no default inference available without degrees of freedom") p.value <- NA } if(is.null(expected) && !is.null(observed)) { expected <- loglin(observed, 1:length(dim(observed)), fit = TRUE, print = FALSE) df <- expected$df expected <- expected$fit } if(is.null(residuals) && !is.null(observed)) residuals <- (observed - expected)/sqrt(expected) ## conduct significance test (if specified) if(is.null(p.value)) p.value <- function(observed, residuals, expected, df) pchisq(sum(as.vector(residuals)^2), df, lower.tail = FALSE) if(!is.function(p.value) && is.na(p.value)) { max.c <- my.c[1] p.value <- NULL } else { if(is.function(p.value)) p.value <- p.value(observed, residuals, expected, df) max.c <- ifelse(p.value < (1-level), my.c[1], my.c[2]) } ## set up function for interpolation of saturation if(!is.function(interpolate)) { col.bins <- sort(interpolate) interpolate <- stepfun(col.bins, seq(0, 1, length.out = length(col.bins) + 1)) col.bins <- sort(unique(c(col.bins, 0, -col.bins))) } else { col.bins <- NULL } ## store color and lty information for legend legend <- NULL if(!is.null(col.bins)) { res2 <- col.bins res2 <- c(head(res2, 1) - 1, res2[-1] - diff(res2)/2, tail(res2, 1) + 1) legend.col <- hcl2hex(ifelse(res2 > 0, my.h[1], my.h[2]), max.c * pmax(pmin(interpolate(abs(res2)), 1), 0), my.l[1] + diff(my.l) * pmax(pmin(interpolate(abs(res2)), 1), 0), ...) lty.bins <- 0 legend.lty <- lty[2:1] legend <- list(col = legend.col, col.bins = col.bins, lty = legend.lty, lty.bins = lty.bins) } ## set up function that computes color/lty from residuals rval <- function(x) { res <- as.vector(x) fill <- hcl2hex(ifelse(res > 0, my.h[1], my.h[2]), max.c * pmax(pmin(interpolate(abs(res)), 1), 0), my.l[1] + diff(my.l) * pmax(pmin(interpolate(abs(res)), 1), 0), ...) dim(fill) <- dim(x) col <- rep(line_col, length.out = length(res)) if(!is.null(eps)) { eps <- abs(eps) col[res > eps] <- hcl2hex(my.h[1], max.c, my.l[2], ...) col[res < -eps] <- hcl2hex(my.h[2], max.c, my.l[2], ...) } dim(col) <- dim(x) ltytmp <- ifelse(x > 0, lty[1], lty[2]) if(!is.null(eps)) ltytmp[abs(x) < abs(eps)] <- lty[1] dim(ltytmp) <- dim(x) return(structure(list(col = col, fill = fill, lty = ltytmp), class = "gpar")) } attr(rval, "legend") <- legend attr(rval, "p.value") <- p.value return(rval) } class(shading_hcl) <- "grapcon_generator" shading_Friendly <- function(observed = NULL, residuals = NULL, expected = NULL, df = NULL, h = c(2/3, 0), lty = 1:2, interpolate = c(2, 4), eps = 0.01, line_col = "black", ...) { shading_hsv(observed = NULL, residuals = NULL, expected = NULL, df = NULL, h = h, v = 1, lty = lty, interpolate = interpolate, eps = eps, line_col = line_col, p.value = NA, ...) } class(shading_Friendly) <- "grapcon_generator" shading_Friendly2 <- function(observed = NULL, residuals = NULL, expected = NULL, df = NULL, lty = 1:2, interpolate = c(2, 4), eps = 0.01, line_col = "black", ...) { shading_hcl(observed = NULL, residuals = NULL, expected = NULL, df = NULL, lty = lty, interpolate = interpolate, eps = eps, line_col = line_col, p.value = NA, ...) } class(shading_Friendly2) <- "grapcon_generator" shading_sieve <- function(observed = NULL, residuals = NULL, expected = NULL, df = NULL, h = c(260, 0), lty = 1:2, interpolate = c(2, 4), eps = 0.01, line_col = "black", ...) { shading_hcl(observed = NULL, residuals = NULL, expected = NULL, df = NULL, h = h, c = 100, l = 50, lty = lty, interpolate = interpolate, eps = eps, line_col = line_col, p.value = NA, ...) } class(shading_sieve) <- "grapcon_generator" shading_max <- function(observed = NULL, residuals = NULL, expected = NULL, df = NULL, h = NULL, c = NULL, l = NULL, lty = 1, eps = NULL, line_col = "black", level = c(0.9, 0.99), n = 1000, ...) { stopifnot(length(dim(observed)) == 2) ## set defaults if(is.null(h)) h <- c(260, 0) if(is.null(c)) c <- c(100, 20) if(is.null(l)) l <- c(90, 50) obs.test <- coindep_test(observed, n = n) col.bins <- obs.test$qdist(sort(level)) rval <- shading_hcl(observed = NULL, residuals = NULL, expected = NULL, df = NULL, h = h, c = c, l = l, interpolate = col.bins, lty = lty, eps = eps, line_col = line_col, p.value = obs.test$p.value, ...) return(rval) } class(shading_max) <- "grapcon_generator" shading_binary <- function(observed = NULL, residuals = NULL, expected = NULL, df = NULL, col = NULL) { ## check col argument if(is.null(col)) col <- hcl2hex(c(260, 0), 50, 70) col <- rep(col, length.out = 2) ## store color information for legend legend <- list(col = col[2:1], col.bins = 0, lty = NULL, lty.bins = NULL) ## set up function that computes color/lty from residuals rval <- function(x) gpar(fill = ifelse(x > 0, col[1], col[2])) ## add meta information for legend attr(rval, "legend") <- legend attr(rval, "p.value") <- NULL rval } class(shading_binary) <- "grapcon_generator" shading_Marimekko <- function(x, fill = NULL, byrow = FALSE) { if (is.null(fill)) fill <- colorspace::rainbow_hcl d <- dim(x) l1 <- if (length(d) > 1L) d[2] else d l2 <- if (length(d) > 1L) d[1] else 1 if (is.function(fill)) fill <- fill(l1) fill <- if (byrow) rep(fill, l2) else rep(fill, each = l2) gpar(col = NA, lty = "solid", fill = array(fill, dim = d)) } shading_diagonal <- function(x, fill = NULL) { if (is.null(fill)) fill <- colorspace::rainbow_hcl d <- dim(x) if (length(d) < 1L) stop("Need matrix or array!") if (d[1] != d[2]) stop("First two dimensions need to be of same length!") if (is.function(fill)) fill <- fill(d[1]) tp = toeplitz(seq_len(d[1])) gpar(col = NA, lty = "solid", fill = array(rep(fill[tp], d[1]), dim = d)) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/shadings.R
########################################################### ## sieveplot sieve <- function(x, ...) UseMethod("sieve") sieve.formula <- function(formula, data = NULL, ..., main = NULL, sub = NULL, subset = NULL) { if (is.logical(main) && main) main <- deparse(substitute(data)) else if (is.logical(sub) && sub) sub <- deparse(substitute(data)) m <- match.call(expand.dots = FALSE) edata <- eval(m$data, parent.frame()) fstr <- strsplit(paste(deparse(formula), collapse = ""), "~") vars <- strsplit(strsplit(gsub(" ", "", fstr[[1]][2]), "\\|")[[1]], "\\+") varnames <- vars[[1]] condnames <- if (length(vars) > 1) vars[[2]] else NULL if (inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) { condind <- NULL dat <- as.table(data) if(all(varnames != ".")) { ind <- match(varnames, names(dimnames(dat))) if (any(is.na(ind))) stop(paste("Can't find", paste(varnames[is.na(ind)], collapse=" / "), "in", deparse(substitute(data)))) if (!is.null(condnames)) { condind <- match(condnames, names(dimnames(dat))) if (any(is.na(condind))) stop(paste("Can't find", paste(condnames[is.na(condind)], collapse=" / "), "in", deparse(substitute(data)))) ind <- c(condind, ind) } dat <- margin.table(dat, ind) } sieve.default(dat, main = main, sub = sub, condvars = if (is.null(condind)) NULL else match(condnames, names(dimnames(dat))), ...) } else { tab <- if ("Freq" %in% colnames(data)) xtabs(formula(paste("Freq~", paste(c(condnames, varnames), collapse = "+"))), data = data, subset = subset) else xtabs(formula(paste("~", paste(c(condnames, varnames), collapse = "+"))), data = data, subset = subset) sieve.default(tab, main = main, sub = sub, ...) } } sieve.default <- function(x, condvars = NULL, gp = NULL, shade = NULL, legend = FALSE, split_vertical = NULL, direction = NULL, spacing = NULL, spacing_args = list(), sievetype = c("observed","expected"), gp_tile = gpar(), scale = 1, main = NULL, sub = NULL, ...) { if (is.logical(main) && main) main <- deparse(substitute(x)) else if (is.logical(sub) && sub) sub <- deparse(substitute(x)) sievetype = match.arg(sievetype) if (is.logical(shade) && shade && is.null(gp)) gp <- if (sievetype == "observed") # shading_sieve(interpolate = 0, lty = c("longdash", "solid")) shading_sieve(interpolate = 0, lty = c("solid", "longdash")) else shading_sieve(interpolate = 0, line_col = "darkgray", eps = Inf, lty = "dotted") if (is.structable(x)) { if (is.null(direction) && is.null(split_vertical)) split_vertical <- attr(x, "split_vertical") x <- as.table(x) } if (is.null(split_vertical)) split_vertical <- FALSE dl <- length(dim(x)) ## splitting argument if (!is.null(direction)) split_vertical <- direction == "v" if (length(split_vertical) == 1) split_vertical <- rep(c(split_vertical, !split_vertical), length.out = dl) if (length(split_vertical) < dl) split_vertical <- rep(split_vertical, length.out = dl) ## condvars if (!is.null(condvars)) { if (is.character(condvars)) condvars <- match(condvars, names(dimnames(x))) x <- aperm(x, c(condvars, seq(dl)[-condvars])) if (is.null(spacing)) spacing <- spacing_conditional } ## spacing argument if (is.null(spacing)) spacing <- if (dl < 3) spacing_equal(sp = 0) else spacing_increase strucplot(x, condvars = if (is.null(condvars)) NULL else length(condvars), core = struc_sieve(sievetype = sievetype, gp_tile = gp_tile, scale = scale), split_vertical = split_vertical, spacing = spacing, spacing_args = spacing_args, main = main, sub = sub, shade = shade, legend = legend, gp = gp, ...) } ## old version (not performant enough) ## ## struc_sieve <- function(sievetype = c("observed", "expected")) { ## sievetype = match.arg(sievetype) ## function(residuals, observed, expected, spacing, gp, split_vertical, prefix = "") { ## dn <- dimnames(expected) ## dnn <- names(dn) ## dx <- dim(expected) ## dl <- length(dx) ## n <- sum(expected) ## ## split workhorse ## split <- function(x, i, name, row, col, rowmargin, colmargin) { ## cotab <- co_table(x, 1) ## margin <- sapply(cotab, sum) ## v <- split_vertical[i] ## d <- dx[i] ## ## compute total cols/rows and build split layout ## dist <- unit.c(unit(margin, "null"), spacing[[i]]) ## idx <- matrix(1:(2 * d), nrow = 2, byrow = TRUE)[-2 * d] ## layout <- if (v) ## grid.layout(ncol = 2 * d - 1, widths = dist[idx]) ## else ## grid.layout(nrow = 2 * d - 1, heights = dist[idx]) ## vproot <- viewport(layout.pos.col = col, layout.pos.row = row, ## layout = layout, name = remove_trailing_comma(name)) ## ## next level: either create further splits, or final viewports ## name <- paste(name, dnn[i], "=", dn[[i]], ",", sep = "") ## row <- col <- rep.int(1, d) ## if (v) col <- 2 * 1:d - 1 else row <- 2 * 1:d - 1 ## proptab <- function(x) x / max(sum(x), 1) ## f <- if (i < dl) { ## if (v) ## function(m) split(cotab[[m]], i + 1, name[m], row[m], col[m], ## colmargin = colmargin * proptab(margin)[m], ## rowmargin = rowmargin) ## else ## function(m) split(cotab[[m]], i + 1, name[m], row[m], col[m], ## colmargin = colmargin, ## rowmargin = rowmargin * proptab(margin)[m]) ## } else { ## if (v) ## function(m) viewport(layout.pos.col = col[m], layout.pos.row = row[m], ## name = remove_trailing_comma(name[m]), ## yscale = c(0, rowmargin), ## xscale = c(0, colmargin * proptab(margin)[m])) ## else ## function(m) viewport(layout.pos.col = col[m], layout.pos.row = row[m], ## name = remove_trailing_comma(name[m]), ## yscale = c(0, rowmargin * proptab(margin)[m]), ## xscale = c(0, colmargin)) ## } ## vpleaves <- structure(lapply(1:d, f), class = c("vpList", "viewport")) ## vpTree(vproot, vpleaves) ## } ## ## start splitting on top, creates viewport-tree ## pushViewport(split(expected + .Machine$double.eps, ## i = 1, name = paste(prefix, "cell:", sep = ""), row = 1, col = 1, ## rowmargin = n, colmargin = n)) ## ## draw rectangles ## mnames <- apply(expand.grid(dn), 1, ## function(i) paste(dnn, i, collapse=",", sep = "=") ## ) ## for (i in seq_along(mnames)) { ## seekViewport(paste(prefix, "cell:", mnames[i], sep = "")) ## vp <- current.viewport() ## gpobj <- structure(lapply(gp, function(x) x[i]), class = "gpar") ## div <- if (sievetype == "observed") observed[i] else expected[i] ## if (div > 0) { ## square.side <- sqrt(vp$yscale[2] * vp$xscale[2] / div) ## ii <- seq(0, vp$xscale[2], by = square.side) ## jj <- seq(0, vp$yscale[2], by = square.side) ## grid.segments(x0 = ii, x1 = ii, y0 = 0, y1 = vp$yscale[2], ## default.units = "native", gp = gpobj) ## grid.segments(x0 = 0, x1 = vp$xscale[2], y0 = jj, y1 = jj, ## default.units = "native", gp = gpobj) ## } ## grid.rect(name = paste(prefix, "rect:", mnames[i], sep = ""), ## gp = gpar(fill = "transparent")) ## } ## } ## } ##class(struc_sieve) <- "grapcon_generator" struc_sieve <- function(sievetype = c("observed", "expected"), gp_tile = gpar(), scale = 1) { sievetype = match.arg(sievetype) function(residuals, observed, expected, spacing, gp, split_vertical, prefix = "") { observed <- scale * observed expected <- scale * expected if (is.null(expected)) stop("Need expected values.") dn <- dimnames(expected) dnn <- names(dn) dx <- dim(expected) dl <- length(dx) n <- sum(expected) ## split workhorse split <- function(x, i, name, row, col, rowmargin, colmargin, index) { cotab <- co_table(x, 1) margin <- sapply(cotab, sum) v <- split_vertical[i] d <- dx[i] ## compute total cols/rows and build split layout dist <- if (d > 1) unit.c(unit(margin, "null"), spacing[[i]]) else unit(margin, "null") idx <- matrix(1:(2 * d), nrow = 2, byrow = TRUE)[-2 * d] layout <- if (v) grid.layout(ncol = 2 * d - 1, widths = dist[idx]) else grid.layout(nrow = 2 * d - 1, heights = dist[idx]) pushViewport(viewport(layout.pos.col = col, layout.pos.row = row, layout = layout, name = paste(prefix, "cell:", remove_trailing_comma(name), sep = ""))) ## next level: either create further splits, or final viewports row <- col <- rep.int(1, d) if (v) col <- 2 * 1:d - 1 else row <- 2 * 1:d - 1 proptab <- function(x) x / max(sum(x), 1) for (m in 1:d) { nametmp <- paste(name, dnn[i], "=", dn[[i]][m], ",", sep = "") if (v) { colmargintmp <- colmargin * proptab(margin)[m] rowmargintmp <- rowmargin } else { rowmargintmp <- rowmargin * proptab(margin)[m] colmargintmp <- colmargin } if (i < dl) split(cotab[[m]], i + 1, nametmp, row[m], col[m], colmargin = colmargintmp, rowmargin = rowmargintmp, index = cbind(index, m)) else { pushViewport(viewport(layout.pos.col = col[m], layout.pos.row = row[m], name = paste(prefix, "cell:", remove_trailing_comma(nametmp), sep = ""), yscale = c(0, rowmargintmp), xscale = c(0, colmargintmp))) gpobj <- structure(lapply(gp, function(x) x[cbind(index, m)]), class = "gpar") ## draw sieve div <- if (sievetype == "observed") observed[cbind(index, m)] else expected[cbind(index, m)] gptmp <- gp_tile gptmp$col <- "transparent" grid.rect(name = paste(prefix, "rect:", nametmp, sep = ""), gp = gptmp) if (div > 0) { square.side <- sqrt(colmargintmp * rowmargintmp / div) ii <- seq(0, colmargintmp, by = square.side) jj <- seq(0, rowmargintmp, by = square.side) grid.segments(x0 = ii, x1 = ii, y0 = 0, y1 = rowmargintmp, default.units = "native", gp = gpobj) grid.segments(x0 = 0, x1 = colmargintmp, y0 = jj, y1 = jj, default.units = "native", gp = gpobj) } gptmp <- gp_tile gptmp$fill <- "transparent" grid.rect(name = paste(prefix, "border:", nametmp, sep = ""), gp = gptmp) } upViewport(1) } } ## start splitting on top, creates viewport-tree split(expected + .Machine$double.eps, i = 1, name = "", row = 1, col = 1, rowmargin = n, colmargin = n, index = cbind()) } } class(struc_sieve) <- "grapcon_generator"
/scratch/gouwar.j/cran-all/cranData/vcd/R/sieve.R
################################################################## ## spacings spacing_equal <- function(sp = unit(0.3, "lines")) { if (!is.unit(sp)) sp <- unit(sp, "lines") function(d, condvars = NULL) lapply(d, function(x) if(x > 1) rep(sp, x - 1) else NA) } class(spacing_equal) <- "grapcon_generator" spacing_dimequal <- function(sp) { if (!is.unit(sp)) sp <- unit(sp, "lines") function(d, condvars = NULL) lapply(seq_along(d), function(i) if(d[i] > 1) rep(sp[i], d[i] - 1) else NA) } class(spacing_dimequal) <- "grapcon_generator" spacing_increase <- function(start = unit(0.3, "lines"), rate = 1.5) { if (!is.unit(start)) start <- unit(start, "lines") function(d, condvars = NULL) { sp <- start * rev(cumprod(c(1, rep.int(rate, length(d) - 1)))) spacing_dimequal(sp)(d = d, condvars = condvars) } } class(spacing_increase) <- "grapcon_generator" spacing_highlighting <- function(start = unit(0.2, "lines"), rate = 1.5) { if (!is.unit(start)) start <- unit(start, "lines") function(d, condvars = NULL) c(spacing_increase(start, rate)(d, condvars)[-length(d)], list(unit(rep(0, d[length(d)]), "lines"))) } class(spacing_highlighting) <- "grapcon_generator" spacing_conditional <- function(sp = unit(0.3, "lines"), start = unit(2, "lines"), rate = 1.8) { condfun <- spacing_increase(start, rate) equalfun <- spacing_equal(sp) equalfun2 <- spacing_equal(start) function(d, condvars) { if (length(d) < 3) return(spacing_equal(sp)(d, condvars)) condvars <- seq(condvars) ret <- vector("list", length(d)) ret[condvars] <- if (length(condvars) < 3) equalfun2(d[condvars]) else condfun(d[condvars]) ret[-condvars] <- equalfun(d[-condvars]) ret } } class(spacing_conditional) <- "grapcon_generator"
/scratch/gouwar.j/cran-all/cranData/vcd/R/spacings.R
spine <- function(x, ...) UseMethod("spine") spine.formula <- function(formula, data = list(), breaks = NULL, ylab_tol = 0.05, off = NULL, main = "", xlab = NULL, ylab = NULL, ylim = c(0, 1), margins = c(5.1, 4.1, 4.1, 3.1), gp = gpar(), name = "spineplot", newpage = TRUE, pop = TRUE, ...) { ## extract x, y from formula mf <- model.frame(formula, data = data) if(NCOL(mf) != 2) stop("`formula' should specify exactly two variables") y <- mf[,1] if(!is.factor(y)) stop("dependent variable should be a factor") x <- mf[,2] if(is.null(xlab)) xlab <- names(mf)[2] if(is.null(ylab)) ylab <- names(mf)[1] spine(x, y, breaks = breaks, ylab_tol = ylab_tol, off = off, main = main, xlab = xlab, ylab = ylab, ylim = ylim, margins = margins, gp = gp, name = name, newpage = newpage, pop = pop, ...) } spine.default <- function(x, y = NULL, breaks = NULL, ylab_tol = 0.05, off = NULL, main = "", xlab = NULL, ylab = NULL, ylim = c(0, 1), margins = c(5.1, 4.1, 4.1, 3.1), gp = gpar(), name = "spineplot", newpage = TRUE, pop = TRUE, ...) { ## either supply a 2-way table (i.e., both y and x are categorical) ## or two variables (y has to be categorical - x can be categorical or numerical) if(missing(y)) { if(length(dim(x)) != 2) stop("a 2-way table has to be specified") tab <- x x.categorical <- TRUE if(is.null(xlab)) xlab <- names(dimnames(tab))[1] if(is.null(ylab)) ylab <- names(dimnames(tab))[2] xnam <- dimnames(tab)[[1]] ynam <- dimnames(tab)[[2]] ny <- NCOL(tab) nx <- NROW(tab) } else { if(!is.factor(y)) stop("dependent variable should be a factor") x.categorical <- is.factor(x) if(!x.categorical) stopifnot(is.numeric(x), is.vector(x)) if(is.null(xlab)) xlab <- deparse(substitute(x)) if(is.null(ylab)) ylab <- deparse(substitute(y)) if(x.categorical) { tab <- table(x, y) xnam <- levels(x) nx <- NROW(tab) } ynam <- levels(y) ny <- length(ynam) } ## graphical parameters if(is.null(gp$fill)) gp$fill <- gray.colors(ny) gp$fill <- rep(gp$fill, length.out = ny) off <- if(!x.categorical) 0 else if(is.null(off)) 0.02 else off/100 if(x.categorical) { ## compute rectangle positions on x axis xat <- c(0, cumsum(prop.table(margin.table(tab, 1)) + off)) } else { ## compute breaks for x if(is.null(breaks)) breaks <- list() if(!is.list(breaks)) breaks <- list(breaks = breaks) breaks <- c(list(x = x), breaks) breaks$plot <- FALSE breaks <- do.call("hist", breaks)$breaks ## categorize x x1 <- cut(x, breaks = breaks, include.lowest = TRUE) ## compute rectangle positions on x axis xat <- c(0, cumsum(prop.table(table(x1)))) ## construct table tab <- table(x1, y) nx <- NROW(tab) } ## compute rectangle positions on y axis yat <- rbind(0, apply(prop.table(tab, 1), 1, cumsum)) ## setup plot if(newpage) grid.newpage() pushViewport(plotViewport(xscale = c(0, 1 + off * (nx-1)), yscale = ylim, default.units = "native", name = name, margins = margins, ...)) ## compute coordinates ybottom <- as.vector(yat[-(ny+1),]) ybottom[ybottom < ylim[1]] <- ylim[1] ybottom[ybottom > ylim[2]] <- ylim[2] ytop <- as.vector(yat[-1,]) ytop[ytop < ylim[1]] <- ylim[1] ytop[ytop > ylim[2]] <- ylim[2] xleft <- rep(xat[1:nx], rep(ny, nx)) xright <- rep(xat[2:(nx+1)] - off, rep(ny, nx)) gp$fill <- rep(gp$fill, nx) ## plot rectangles grid.rect(xleft, ybottom, width = (xright-xleft), height = (ytop-ybottom), just = c("left", "bottom"), default.units = "native", gp = gp) ## axes ## 1: either numeric or level names if(x.categorical) grid.text(x = unit((xat[1:nx] + xat[2:(nx+1)] - off)/2, "native"), y = unit(-1.5, "lines"), label = xnam, check.overlap = TRUE) else grid.xaxis(at = xat, label = breaks) ## 2: axis with level names of y yat <- yat[,1] equidist <- any(diff(yat) < ylab_tol) yat <- if(equidist) seq(1/(2*ny), 1-1/(2*ny), by = 1/ny) else (yat[-1] + yat[-length(yat)])/2 grid.text(x = unit(-1.5, "lines"), y = unit(yat, "native"), label = ynam, rot = 90, check.overlap = TRUE) ## 3: none ## 4: simple numeric grid.yaxis(main = FALSE) ## annotation grid.text(xlab, y = unit(-3.5, "lines")) grid.text(ylab, x = unit(-3, "lines"), rot = 90) grid.text(main, y = unit(1, "npc") + unit(2, "lines"), gp = gpar(fontface = "bold")) ## pop if(pop) popViewport() ## return table visualized names(dimnames(tab)) <- c(xlab, ylab) invisible(tab) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/spine.R
################################################################ ### strucplot - generic plot framework for mosaic-like layouts ### 2 core functions are provided: struc_mosaic and struc_assoc ################################################################ strucplot <- function(## main parameters x, residuals = NULL, expected = NULL, condvars = NULL, shade = NULL, type = c("observed", "expected"), residuals_type = NULL, df = NULL, ## layout split_vertical = NULL, spacing = spacing_equal, spacing_args = list(), gp = NULL, gp_args = list(), labeling = labeling_border, labeling_args = list(), core = struc_mosaic, core_args = list(), legend = NULL, legend_args = list(), main = NULL, sub = NULL, margins = unit(3, "lines"), title_margins = NULL, legend_width = NULL, ## control parameters main_gp = gpar(fontsize = 20), sub_gp = gpar(fontsize = 15), newpage = TRUE, pop = TRUE, return_grob = FALSE, keep_aspect_ratio = NULL, prefix = "", ... ) { ## default behaviour of shade if (is.null(shade)) shade <- !is.null(gp) || !is.null(expected) type <- match.arg(type) if (is.null(residuals)) { residuals_type <- if (is.null(residuals_type)) "pearson" else match.arg(tolower(residuals_type), c("pearson", "deviance", "ft")) } else { if (is.null(residuals_type)) residuals_type <- "" } ## convert structable object if (is.structable(x)) { if (is.null(split_vertical)) split_vertical <- attr(x, "split_vertical") x <- as.table(x) } if (is.null(split_vertical)) split_vertical <- FALSE ## table characteristics d <- dim(x) dl <- length(d) dn <- dimnames(x) if (is.null(dn)) dn <- dimnames(x) <- lapply(d, seq) dnn <- names(dimnames(x)) if (is.null(dnn)) dnn <- names(dn) <- names(dimnames(x)) <- LETTERS[1:dl] ## replace NAs by 0 if (any(nas <- is.na(x))) x[nas] <- 0 ## model fitting: ## calculate df and expected if needed ## (used for inference in some shading (generating) functions). ## note: will *not* be calculated if residuals are given if ((is.null(expected) && is.null(residuals)) || !is.numeric(expected)) { if (!is.null(df)) warning("Using calculated degrees of freedom.") if (inherits(expected, "formula")) { fm <- loglm(expected, x, fitted = TRUE) expected <- fitted(fm) df <- fm$df } else { if (is.null(expected)) expected <- if (is.null(condvars)) as.list(1:dl) else lapply((condvars + 1):dl, c, seq(condvars)) fm <- loglin(x, expected, fit = TRUE, print = FALSE) expected <- fm$fit df <- fm$df } } ## compute residuals if (is.null(residuals)) residuals <- switch(residuals_type, pearson = (x - expected) / sqrt(ifelse(expected > 0, expected, 1)), deviance = { tmp <- 2 * (x * log(ifelse(x == 0, 1, x / ifelse(expected > 0, expected, 1))) - (x - expected)) tmp <- sqrt(pmax(tmp, 0)) ifelse(x > expected, tmp, -tmp) }, ft = sqrt(x) + sqrt(x + 1) - sqrt(4 * expected + 1) ) ## replace NAs by 0 if (any(nas <- is.na(residuals))) residuals[nas] <- 0 ## splitting if (length(split_vertical) == 1) split_vertical <- rep(c(split_vertical, !split_vertical), length.out = dl) if (is.null(keep_aspect_ratio)) keep_aspect_ratio <- dl < 3 ## spacing if (is.function(spacing)) { if (inherits(spacing, "grapcon_generator")) spacing <- do.call("spacing", spacing_args) spacing <- spacing(d, condvars) } ## gp (color, fill, lty, etc.) argument if (shade) { if (is.null(gp)) gp <- shading_hcl if (is.function(gp)) { if (is.null(legend) || (is.logical(legend) && legend)) legend <- legend_resbased gpfun <- if (inherits(gp, "grapcon_generator")) do.call("gp", c(list(x, residuals, expected, df), as.list(gp_args))) else gp gp <- gpfun(residuals) } else if (!is.null(legend) && !(is.logical(legend) && !legend)) stop("gp argument must be a shading function for drawing a legend") } else { if(!is.null(gp)) { warning("gp parameter ignored since shade = FALSE") gp <- NULL } } ## choose gray when no shading is used if (is.null(gp)) gp <- gpar(fill = grey(0.8)) ## recycle gpar values in the *first* dimension size <- prod(d) FUN <- function(par) { if (is.structable(par)) par <- as.table(par) if (length(par) < size || is.null(dim(par))) array(par, dim = d) else par } gp <- structure(lapply(gp, FUN), class = "gpar") ## set up page if (newpage) grid.newpage() if (keep_aspect_ratio) pushViewport(viewport(width = 1, height = 1, default.units = "snpc")) pushViewport(vcdViewport(mar = margins, oma = title_margins, legend = shade && !(is.null(legend) || is.logical(legend) && !legend), main = !is.null(main), sub = !is.null(sub), keep_aspect_ratio = keep_aspect_ratio, legend_width = legend_width, prefix = prefix)) ## legend if (inherits(legend, "grapcon_generator")) legend <- do.call("legend", legend_args) if (shade && !is.null(legend) && !(is.logical(legend) && !legend)) { seekViewport(paste(prefix, "legend", sep = "")) residuals_type <- switch(residuals_type, deviance = "deviance\nresiduals:", ft = "Freeman-Tukey\nresiduals:", pearson = "Pearson\nresiduals:", residuals_type) legend(residuals, gpfun, residuals_type) } ## titles if (!is.null(main)) { seekViewport(paste(prefix, "main", sep = "")) if (is.logical(main) && main) main <- deparse(substitute(x)) grid.text(main, gp = main_gp) } if (!is.null(sub)) { seekViewport(paste(prefix, "sub", sep = "")) if (is.logical(sub) && sub && is.null(main)) sub <- deparse(substitute(x)) grid.text(sub, gp = sub_gp) } ## make plot seekViewport(paste(prefix, "plot", sep = "")) if (inherits(core, "grapcon_generator")) core <- do.call("core", core_args) core(residuals = residuals, observed = if (type == "observed") x else expected, expected = if (type == "observed") expected else x, spacing = spacing, gp = gp, split_vertical = split_vertical, prefix = prefix) upViewport(1) ## labels if (is.logical(labeling)) labeling <- if (labeling) labeling_border else NULL if (!is.null(labeling)) { if (inherits(labeling, "grapcon_generator")) labeling <- do.call("labeling", c(labeling_args, list(...))) labeling(dn, split_vertical, condvars, prefix) } ## pop/move up viewport seekViewport(paste(prefix, "base", sep = "")) ## one more up if sandwich-mode if (pop) popViewport(1 + keep_aspect_ratio) else upViewport(1 + keep_aspect_ratio) ## return visualized table if (return_grob) invisible(structure(structable(if (type == "observed") x else expected, split_vertical = split_vertical), grob = grid.grab() ) ) else invisible(structable(if (type == "observed") x else expected, split_vertical = split_vertical)) } vcdViewport <- function(mar = rep.int(2.5, 4), legend_width = unit(5, "lines"), oma = NULL, legend = FALSE, main = FALSE, sub = FALSE, keep_aspect_ratio = TRUE, prefix = "") { ## process parameters if (is.null(legend_width)) legend_width <- unit(5 * legend, "lines") if (!is.unit(legend_width)) legend_width <- unit(legend_width, "lines") if (legend && !main && !sub && keep_aspect_ratio) main <- sub <- TRUE mar <- if (!is.unit(mar)) unit(pexpand(mar, 4, rep.int(2.5, 4), c("top","right","bottom","left")), "lines") else rep(mar, length.out = 4) if (is.null(oma)) { space <- if (legend && keep_aspect_ratio) legend_width + mar[2] + mar[4] - mar[1] - mar[3] else unit(0, "lines") oma <- if (main && sub) max(unit(2, "lines"), 0.5 * space) else if (main) unit.c(max(unit(2, "lines"), space), unit(0, "lines")) else if (sub) unit.c(unit(0, "lines"), max(unit(2, "lines"), space)) else 0.5 * space } oma <- if (!is.unit(oma)) unit(pexpand(oma, 2, rep.int(2, 2), c("top","bottom")), "lines") else rep(oma, length.out = 2) ## set up viewports vpPlot <- vpStack(viewport(layout.pos.col = 2, layout.pos.row = 3), viewport(width = 1, height = 1, name = paste(prefix, "plot", sep = ""), default.units = if (keep_aspect_ratio) "snpc" else "npc")) vpMarginBottom <- viewport(layout.pos.col = 2, layout.pos.row = 4, name = paste(prefix, "margin_bottom", sep = "")) vpMarginLeft <- viewport(layout.pos.col = 1, layout.pos.row = 3, name = paste(prefix, "margin_left", sep = "")) vpMarginTop <- viewport(layout.pos.col = 2, layout.pos.row = 2, name = paste(prefix, "margin_top", sep = "")) vpMarginRight <- viewport(layout.pos.col = 3, layout.pos.row = 3, name = paste(prefix, "margin_right", sep = "")) vpCornerTL <- viewport(layout.pos.col = 1, layout.pos.row = 2, name = paste(prefix, "corner_top_left", sep = "")) vpCornerTR <- viewport(layout.pos.col = 3, layout.pos.row = 2, name = paste(prefix, "corner_top_right", sep = "")) vpCornerBL <- viewport(layout.pos.col = 1, layout.pos.row = 4, name = paste(prefix, "corner_bottom_left", sep = "")) vpCornerBR <- viewport(layout.pos.col = 3, layout.pos.row = 4, name = paste(prefix, "corner_bottom_right", sep = "")) vpLegend <- viewport(layout.pos.col = 4, layout.pos.row = 3, name = paste(prefix, "legend", sep = "")) vpLegendTop <- viewport(layout.pos.col = 4, layout.pos.row = 2, name = paste(prefix, "legend_top", sep = "")) vpLegendSub <- viewport(layout.pos.col = 4, layout.pos.row = 4, name = paste(prefix, "legend_sub", sep = "")) vpBase <- viewport(layout = grid.layout(5, 4, widths = unit.c(mar[4], unit(1, "null"), mar[2], legend_width), heights = unit.c(oma[1], mar[1], unit(1, "null"), mar[3], oma[2])), name = paste(prefix, "base", sep = "")) vpMain <- viewport(layout.pos.col = 1:4, layout.pos.row = 1, name = paste(prefix, "main", sep = "")) vpSub <- viewport(layout.pos.col = 1:4, layout.pos.row = 5, name = paste(prefix, "sub", sep = "")) vpTree(vpBase, vpList(vpMain, vpMarginBottom, vpMarginLeft, vpMarginTop, vpMarginRight, vpLegendTop, vpLegend, vpLegendSub, vpCornerTL, vpCornerTR, vpCornerBL, vpCornerBR, vpPlot, vpSub)) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/strucplot.R
######################################### ## structable structable <- function(x, ...) UseMethod("structable") structable.formula <- function(formula, data = NULL, direction = NULL, split_vertical = NULL, ..., subset, na.action) { if (missing(formula) || !inherits(formula, "formula")) stop("formula is incorrect or missing") m <- match.call(expand.dots = FALSE) edata <- eval(m$data, parent.frame()) if (!is.null(direction)) split_vertical <- direction == "v" if (is.structable(data)) { split_vertical <- attr(data, "split_vertical") data <- as.table(data) } if (is.null(split_vertical)) split_vertical <- FALSE if (length(formula) == 3 && formula[[2]] == "Freq") formula[[2]] = NULL ## only rhs present without `.' in lhs => xtabs-interface if (length(formula) != 3) { if (formula[[1]] == "~") { if (inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) { data <- as.table(data) varnames <- attr(terms(formula, allowDotAsName = TRUE), "term.labels") dnames <- names(dimnames(data)) di <- match(varnames, dnames) if (any(is.na(di))) stop("incorrect variable names in formula") if (all(varnames != ".")) data <- margin.table(data, di) return(structable(data, split_vertical = split_vertical, ...)) } else if (is.data.frame(data)) { if ("Freq" %in% colnames(data)) return(structable(xtabs(formula(paste("Freq", deparse(formula))), data = data), split_vertical = split_vertical, ...)) else return(structable(xtabs(formula, data), split_vertical = split_vertical, ...)) } else { if (is.matrix(edata)) m$data <- as.data.frame(data) m$... <- m$split_vertical <- m$direction <- NULL m[[1L]] <- quote(stats::model.frame) mf <- eval(m, parent.frame()) return(structable(table(mf), split_vertical = split_vertical, ...)) } } else stop("formula must have both left and right hand sides") } ## `ftable' behavior if (any(attr(terms(formula, allowDotAsName = TRUE), "order") > 1)) stop("interactions are not allowed") rvars <- attr(terms(formula[-2], allowDotAsName = TRUE), "term.labels") cvars <- attr(terms(formula[-3], allowDotAsName = TRUE), "term.labels") rhs.has.dot <- any(rvars == ".") lhs.has.dot <- any(cvars == ".") if (lhs.has.dot && rhs.has.dot) stop(paste("formula has", sQuote("."), "in both left and right hand side")) if (inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) { if (inherits(edata, "ftable")) data <- as.table(data) dnames <- names(dimnames(data)) rvars <- pmatch(rvars, dnames) cvars <- pmatch(cvars, dnames) if (rhs.has.dot) rvars <- seq_along(dnames)[-cvars] else if (any(is.na(rvars))) stop("incorrect variable names in rhs of formula") if (lhs.has.dot) cvars <- seq_along(dnames)[-rvars] else if (any(is.na(cvars))) stop("incorrect variable names in lhs of formula") split_vertical <- c(rep(FALSE, length(rvars)), rep(TRUE, length(cvars))) structable(margin.table(data, c(rvars, cvars)), split_vertical = split_vertical, ...) } else { if (is.matrix(edata)) m$data <- as.data.frame(data) m$... <- m$split_vertical <- m$direction <- NULL if (!is.null(data) && is.environment(data)) { dnames <- names(data) if (rhs.has.dot) rvars <- seq_along(dnames)[-cvars] if (lhs.has.dot) cvars <- seq_along(dnames)[-rvars] } else { if (lhs.has.dot || rhs.has.dot) stop("cannot use dots in formula with given data") } if ("Freq" %in% colnames(m$data)) m$formula <- formula(paste("Freq~", paste(c(rvars, cvars), collapse = "+"))) else m$formula <- formula(paste("~", paste(c(rvars, cvars), collapse = "+"))) m[[1]] <- as.name("xtabs") mf <- eval(m, parent.frame()) split_vertical <- c(rep(FALSE, length(rvars)), rep(TRUE, length(cvars))) structable(mf, split_vertical = split_vertical, ...) } } structable.default <- function(..., direction = NULL, split_vertical = FALSE) { ## several checks & transformations for arguments args <- list(...) if (length(args) == 0) stop("Nothing to tabulate") x <- args[[1]] x <- if (is.list(x)) table(x) else if (inherits(x, "ftable")) as.table(x) else if (!(is.array(x) && length(dim(x)) > 1 || inherits(x, "table"))) do.call("table", as.list(substitute(list(...)))[-1]) else x if (is.null(dimnames(x))) dimnames(x) <- lapply(dim(x), function(i) letters[seq_len(i)]) if (is.null(names(dimnames(x)))) names(dimnames(x)) <- LETTERS[seq_along(dim(x))] idx <- sapply(names(dimnames(x)), nchar) < 1 if(any(idx)) names(dimnames(x))[idx] <- LETTERS[seq_len(sum(idx))] ## splitting argument dl <- length(dim(x)) if (!is.null(direction)) split_vertical <- direction == "v" if (length(split_vertical) == 1) split_vertical <- rep(c(split_vertical, !split_vertical), length.out = dl) if (length(split_vertical) < dl) split_vertical <- rep(split_vertical, length.out = dl) ## permute & reshape ret <- base::aperm(x, c(rev(which(!split_vertical)), rev(which(split_vertical)))) dn <- dimnames(x) rv <- dn[split_vertical] cv <- dn[!split_vertical] rl <- if (length(rv)) sapply(rv, length) else 1 cl <- if (length(cv)) sapply(cv, length) else 1 dim(ret) <- c(prod(cl), prod(rl)) ## add dimnames attr(ret, "dnames") <- dn attr(ret, "split_vertical") <- split_vertical ## add dimension attributes in ftable-format attr(ret, "col.vars") <- rv attr(ret, "row.vars") <- cv class(ret) <- c("structable", "ftable") ret } "[[.structable" <- function(x, ...) { if(nargs() > 3) stop("Incorrect number of dimensions (max: 2).") args <- if (nargs() < 3) list(..1) else .massage_args(...) args <- lapply(args, function(x) if (is.logical(x)) which(x) else x) ## handle one-arg cases if (nargs() < 3) if (length(args[[1]]) > 1) ## resolve calls like x[[c(1,2)]] return(x[[ args[[1]][1] ]] [[ args[[1]][-1] ]]) else ## resolve x[[foo]] return(if (attr(x, "split_vertical")[1]) x[[,args[[1]] ]] else x[[args[[1]],]]) ## handle calls like x[[c(1,2), c(3,4)]] if (length(args[[1]]) > 1 && length(args[[2]]) > 1) return(x[[ args[[1]][1], args[[2]][1] ]] [[ args[[1]][-1], args[[2]][-1] ]]) ## handle calls like x[[c(1,2), 3]] if (length(args[[1]]) > 1) return(x[[ args[[1]][1], args[[2]] ]] [[ args[[1]][-1], ]]) ## handle calls like x[[1, c(1,3)]] if (length(args[[2]]) > 1) return(x[[ args[[1]], args[[2]][1] ]] [[ , args[[2]][-1] ]]) ## final cases like x[[1,2]] or x[[1,]] or x[[,1]] dnames <- attr(x, "dnames") split <- attr(x, "split_vertical") rv <- dnames[!split] cv <- dnames[split] lsym <- is.symbol(args[[1]]) rsym <- is.symbol(args[[2]]) if (!lsym) { rstep <- dim(unclass(x))[1] / length(rv[[1]]) if (is.character(args[[1]])) args[[1]] <- match(args[[1]], rv[[1]]) } if (!rsym) { cstep <- dim(unclass(x))[2] / length(cv[[1]]) if (is.character(args[[2]])) args[[2]] <- match(args[[2]], cv[[1]]) } lind <- if (!lsym) (1 + (args[[1]] - 1) * rstep) : (args[[1]] * rstep) else 1:nrow(unclass(x)) rind <- if (!rsym) (1 + (args[[2]] - 1) * cstep) : (args[[2]] * cstep) else 1:ncol(unclass(x)) ret <- unclass(x)[lind, rind, drop = FALSE] if (!lsym) { i <- which(!split)[1] split <- split[-i] dnames <- dnames[-i] } if (!rsym) { i <- which(split)[1] split <- split[-i] dnames <- dnames[-i] } attr(ret, "split_vertical") <- split attr(ret, "dnames") <- dnames ## add dimension attributes in ftable-format attr(ret, "col.vars") <- dnames[split] attr(ret, "row.vars") <- dnames[!split] class(ret) <- class(x) ret } "[[<-.structable" <- function(x, ..., value) { args <- if (nargs() < 4) list(..1) else .massage_args(...) ## handle one-arg cases if (nargs() < 4) return(if (length(args[[1]]) > 1) ## resolve calls like x[[c(1,2)]]<-value Recall(x, args[[1]][1], value = Recall(x[[ args[[1]][1] ]], args[[1]][-1], value = value)) else ## resolve x[[foo]]<-value if (attr(x, "split_vertical")[1]) Recall(x,,args[[1]], value = value) else Recall(x,args[[1]],, value = value) ) ## handle calls like x[[c(1,2), c(3,4)]]<-value if (length(args[[1]]) > 1 && length(args[[2]]) > 1) return(Recall(x, args[[1]][1], args[[2]][1], value = Recall(x[[ args[[1]][1], args[[2]][1] ]], args[[1]][-1], args[[2]][-1], value = value))) ## handle calls like x[[c(1,2), 3]]<-value if (length(args[[1]]) > 1) return(Recall(x, args[[1]][1], args[[2]], value = Recall(x[[ args[[1]][1], args[[2]] ]], args[[1]][-1], ,value = value))) ## handle calls like x[[1, c(1,3)]]<-value if (length(args[[2]]) > 1) return(Recall(x, args[[1]], args[[2]][1], value = Recall(x[[ args[[1]], args[[2]][1] ]],, args[[2]][-1], value = value))) ## final cases like x[[1,2]]<-value or x[[1,]]<-value or x[[,1]]<-value dnames <- attr(x, "dnames") split <- attr(x, "split_vertical") rv <- dnames[!split] cv <- dnames[split] lsym <- is.symbol(args[[1]]) rsym <- is.symbol(args[[2]]) if (!lsym) { rstep <- dim(unclass(x))[1] / length(rv[[1]]) if (is.character(args[[1]])) args[[1]] <- match(args[[1]], rv[[1]]) } if (!rsym) { cstep <- dim(unclass(x))[2] / length(cv[[1]]) if (is.character(args[[2]])) args[[2]] <- match(args[[2]], cv[[1]]) } lind <- if (!lsym) (1 + (args[[1]] - 1) * rstep) : (args[[1]] * rstep) else 1:nrow(unclass(x)) rind <- if (!rsym) (1 + (args[[2]] - 1) * cstep) : (args[[2]] * cstep) else 1:ncol(unclass(x)) ret <- unclass(x) ret[lind, rind] <- value class(ret) <- class(x) ret } "[.structable" <- function(x, ...) { if(nargs() > 3) stop("Incorrect number of dimensions (max: 2).") args <- if (nargs() < 3) list(..1) else .massage_args(...) args <- lapply(args, function(x) if (is.logical(x)) which(x) else x) ## handle one-arg cases if (nargs() < 3) return(if (attr(x, "split_vertical")[1]) x[,args[[1]] ] else x[args[[1]],]) ## handle calls like x[c(1,2), foo] if (length(args[[1]]) > 1) return(do.call(rbind, lapply(args[[1]], function(i) x[i, args[[2]]]))) ## handle calls like x[foo, c(1,3)] if (length(args[[2]]) > 1) return(do.call(cbind, lapply(args[[2]], function(i) x[args[[1]], i]))) ## final cases like x[1,2] or x[1,] or x[,1] dnames <- attr(x, "dnames") split <- attr(x, "split_vertical") rv <- dnames[!split] cv <- dnames[split] lsym <- is.symbol(args[[1]]) rsym <- is.symbol(args[[2]]) if (!lsym) { rstep <- dim(unclass(x))[1] / length(rv[[1]]) if (is.character(args[[1]])) args[[1]] <- match(args[[1]], rv[[1]]) } if (!rsym) { cstep <- dim(unclass(x))[2] / length(cv[[1]]) if (is.character(args[[2]])) args[[2]] <- match(args[[2]], cv[[1]]) } lind <- if (!lsym) (1 + (args[[1]] - 1) * rstep) : (args[[1]] * rstep) else 1:nrow(unclass(x)) rind <- if (!rsym) (1 + (args[[2]] - 1) * cstep) : (args[[2]] * cstep) else 1:ncol(unclass(x)) ret <- unclass(x)[lind, rind, drop = FALSE] if (!lsym) { i <- which(!split)[1] dnames[[i]] <- dnames[[i]][args[[1]]] } if (!rsym) { i <- which(split)[1] dnames[[i]] <- dnames[[i]][args[[2]]] } attr(ret, "split_vertical") <- split attr(ret, "dnames") <- dnames ## add dimension attributes in ftable-format attr(ret, "col.vars") <- dnames[split] attr(ret, "row.vars") <- dnames[!split] class(ret) <- class(x) ret } "[<-.structable" <- function(x, ..., value) { args <- if (nargs() < 4) list(..1) else .massage_args(...) ## handle one-arg cases if (nargs() < 4) return(## resolve x[foo] if (attr(x, "split_vertical")[1]) Recall(x,,args[[1]], value = value) else Recall(x,args[[1]],, value = value) ) ## handle calls like x[c(1,2), 3] if (length(args[[1]]) > 1) { for (i in seq_along(args[[1]])) x[ args[[1]][i], args[[2]] ] <- value[i,] return(x) } ## handle calls like x[1, c(2,3)] if (length(args[[2]]) > 1) { for (i in seq_along(args[[2]])) x[ args[[1]], args[[2]][i] ] <- value[,i] return(x) } ## final cases like x[1,2] or x[1,] or x[,1] dnames <- attr(x, "dnames") split <- attr(x, "split_vertical") rv <- dnames[!split] cv <- dnames[split] lsym <- is.symbol(args[[1]]) rsym <- is.symbol(args[[2]]) if (!lsym) { rstep <- dim(unclass(x))[1] / length(rv[[1]]) if (is.character(args[[1]])) args[[1]] <- match(args[[1]], rv[[1]]) } if (!rsym) { cstep <- dim(unclass(x))[2] / length(cv[[1]]) if (is.character(args[[2]])) args[[2]] <- match(args[[2]], cv[[1]]) } lind <- if (!lsym) (1 + (args[[1]] - 1) * rstep) : (args[[1]] * rstep) else 1:nrow(unclass(x)) rind <- if (!rsym) (1 + (args[[2]] - 1) * cstep) : (args[[2]] * cstep) else 1:ncol(unclass(x)) ret <- unclass(x) ret[lind, rind] <- value class(ret) <- class(x) ret } cbind.structable <- function(..., deparse.level = 1) { mergetables <- function(t1, t2) { ret <- cbind(unclass(t1),unclass(t2)) class(ret) <- class(t1) attr(ret, "split_vertical") <- attr(t1, "split_vertical") attr(ret, "dnames") <- attr(t1, "dnames") attr(ret, "row.vars") <- attr(t1, "row.vars") attr(ret, "col.vars") <- attr(t1, "col.vars") attr(ret, "col.vars")[[1]] <- c(attr(t1, "col.vars")[[1]],attr(t2, "col.vars")[[1]]) if (length(unique(attr(ret, "col.vars")[[1]])) != length(attr(ret, "col.vars")[[1]])) stop("Levels of factor(s) to be merged must be unique.") attr(ret, "dnames")[names(attr(ret, "col.vars"))] <- attr(ret, "col.vars") ret } args <- list(...) if (length(args) < 2) return(args[[1]]) ret <- mergetables(args[[1]], args[[2]]) if (length(args) > 2) do.call(cbind, c(list(ret), args[-(1:2)])) else ret } rbind.structable <- function(..., deparse.level = 1) { mergetables <- function(t1, t2) { ret <- rbind(unclass(t1),unclass(t2)) class(ret) <- class(t1) attr(ret, "split_vertical") <- attr(t1, "split_vertical") attr(ret, "dnames") <- attr(t1, "dnames") attr(ret, "row.vars") <- attr(t1, "row.vars") attr(ret, "col.vars") <- attr(t1, "col.vars") attr(ret, "row.vars")[[1]] <- c(attr(t1, "row.vars")[[1]],attr(t2, "row.vars")[[1]]) if (length(unique(attr(ret, "row.vars")[[1]])) != length(attr(ret, "row.vars")[[1]])) stop("Levels of factor(s) to be merged must be unique.") attr(ret, "dnames")[names(attr(ret, "row.vars"))] <- attr(ret, "row.vars") ret } args <- list(...) if (length(args) < 2) return(args[[1]]) ret <- mergetables(args[[1]], args[[2]]) if (length(args) > 2) do.call(rbind, c(list(ret), args[-(1:2)])) else ret } as.table.structable <- function(x, ...) { class(x) <- "ftable" ret <- NextMethod("as.table", object = x) structure(base::aperm(ret, match(names(attr(x, "dnames")), names(dimnames(ret)))), class = "table") } plot.structable <- function(x, ...) mosaic(x, ...) t.structable <- function(x) { ret <- t.default(x) attr(ret, "split_vertical") <- !attr(ret, "split_vertical") hold <- attr(ret, "row.vars") attr(ret, "row.vars") = attr(ret, "col.vars") attr(ret, "col.vars") = hold ret } is.structable <- function(x) inherits(x, "structable") dim.structable <- function(x) as.integer(sapply(attr(x, "dnames"), length)) print.structable <- function(x, ...) { class(x) <- "ftable" NextMethod("print", object = x) } dimnames.structable <- function(x) attr(x,"dnames") as.vector.structable <- function(x, ...) as.vector(as.table(x), ...) ## FIXME: copy as.matrix.ftable, committed to R-devel on 2014/1/12 ## replace by call to as.matrix.ftable when this becomes stable as_matrix_ftable <- function (x, sep = "_", ...) { if (!inherits(x, "ftable")) stop("'x' must be an \"ftable\" object") make_dimnames <- function(vars) { structure(list(do.call(paste, c(rev(expand.grid(rev(vars))), list(sep = sep)))), names = paste(collapse = sep, names(vars))) } structure(unclass(x), dimnames = c(make_dimnames(attr(x, "row.vars")), make_dimnames(attr(x, "col.vars"))), row.vars = NULL, col.vars = NULL) } as.matrix.structable <- function(x, sep="_", ...) { structure(as_matrix_ftable(x, sep, ...), dnames = NULL, split_vertical = NULL ) } length.structable <- function(x) dim(x)[1] is.na.structable <- function(x) sapply(seq_along(x), function(sub) any(is.na(sub))) str.structable <- function(object, ...) str(unclass(object), ...) find.perm <- function(vec1, vec2) { unlist(Map(function(x) which(x == vec2), vec1)) } aperm.structable <- function(a, perm, resize=TRUE, ...){ newtable <- aperm(as.table(a), perm = perm, resize = resize, ...) if (!is.numeric(perm)) perm <- find.perm(names(dimnames(newtable)), names(dimnames(a))) structable(newtable, split_vertical = attr(a, "split_vertical")[perm]) } ############# helper function .massage_args <- function(...) { args <- vector("list", 2) args[[1]] <- if(missing(..1)) as.symbol("grrr") else ..1 args[[2]] <- if(missing(..2)) as.symbol("grrr") else ..2 args }
/scratch/gouwar.j/cran-all/cranData/vcd/R/structable.R
independence_table <- function(x, frequency = c("absolute", "relative")) { if (!is.array(x)) stop("Need array of absolute frequencies!") frequency <- match.arg(frequency) n <- sum(x) x <- x / n d <- dim(x) ## build margins margins <- lapply(1:length(d), function(i) apply(x, i, sum)) ## multiply all combinations & reshape tab <- array(apply(expand.grid(margins), 1, prod), d, dimnames = dimnames(x)) if (frequency == "relative") tab else tab * n } mar_table <- function(x) { if(!is.matrix(x)) stop("Function only defined for 2-way tables.") tab <- rbind(cbind(x, TOTAL = rowSums(x)), TOTAL = c(colSums(x), sum(x))) names(dimnames(tab)) <- names(dimnames(x)) tab } table2d_summary <- function(object, margins = TRUE, percentages = FALSE, conditionals = c("none", "row", "column"), chisq.test = TRUE, ... ) { ret <- list() if (chisq.test) ret$chisq <- summary.table(object, ...) if(is.matrix(object)) { conditionals <- match.arg(conditionals) tab <- array(0, c(dim(object) + margins, 1 + percentages + (conditionals != "none"))) ## frequencies tab[,,1] <- if(margins) mar_table(object) else object ## percentages if(percentages) { tmp <- prop.table(object) tab[,,2] <- 100 * if(margins) mar_table(tmp) else tmp } ## conditional distributions if(conditionals != "none") { tmp <- prop.table(object, margin = 1 + (conditionals == "column")) tab[,,2 + percentages] <- 100 * if(margins) mar_table(tmp) else tmp } ## dimnames dimnames(tab) <- c(dimnames(if(margins) mar_table(object) else object), list(c("freq", if(percentages) "%", switch(conditionals, row = "row%", column = "col%") ) ) ) ## patch row% / col% margins if(conditionals == "row") tab[dim(tab)[1],,2 + percentages] <- NA if(conditionals == "column") tab[,dim(tab)[2],2 + percentages] <- NA ret$table <- tab } class(ret) <- "table2d_summary" ret } print.table2d_summary <- function (x, digits = max(1, getOption("digits") - 3), ...) { if (!is.null(x$table)) if(dim(x$table)[3] == 1) print(x$table[,,1], digits = digits, ...) else print(ftable(aperm(x$table, c(1,3,2))), 2, digits = digits, ...) cat("\n") if (!is.null(x$chisq)) print.summary.table(x$chisq, digits, ...) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/tabletools.R
"ternaryplot" <- function (x, scale = 1, dimnames = NULL, dimnames_position = c("corner", "edge", "none"), dimnames_color = "black", dimnames_rot = c(-60, 60, 0), id = NULL, id_color = "black", id_just = c("center", "center"), coordinates = FALSE, grid = TRUE, grid_color = "gray", labels = c("inside", "outside", "none"), labels_color = "darkgray", labels_rot = c(120, -120, 0), border = "black", bg = "white", pch = 19, cex = 1, prop_size = FALSE, col = "red", main = "ternary plot", newpage = TRUE, pop = TRUE, return_grob = FALSE, ...) { ## parameter handling labels <- match.arg(labels) if (grid == TRUE) grid <- "dotted" if (coordinates) id <- paste("(",round(x[,1] * scale, 1),",", round(x[,2] * scale, 1),",", round(x[,3] * scale, 1),")", sep="") dimnames_position <- match.arg(dimnames_position) if(is.null(dimnames) && dimnames_position != "none") dimnames <- colnames(x) if(is.logical(prop_size) && prop_size) prop_size <- 3 ## some error handling if(ncol(x) != 3) stop("Need a matrix with 3 columns") if(any(x < 0)) stop("X must be non-negative") s <- rowSums(x) if(any(s <= 0)) stop("each row of X must have a positive sum") ## rescaling x <- x / s ## prepare plot top <- sqrt(3) / 2 if (newpage) grid.newpage() xlim <- c(-0.03, 1.03) ylim <- c(-1, top) pushViewport(viewport(width = unit(1, "snpc"))) if (!is.null(main)) grid.text(main, y = 0.9, gp = gpar(fontsize = 18, fontstyle = 1)) pushViewport(viewport(width = 0.8, height = 0.8, xscale = xlim, yscale = ylim, name = "plot")) eps <- 0.01 ## coordinates of point P(a,b,c): xp = b + c/2, yp = c * sqrt(3)/2 ## triangle grid.polygon(c(0, 0.5, 1), c(0, top, 0), gp = gpar(fill = bg, col = border), ...) ## title, labeling if (dimnames_position == "corner") { grid.text(x = c(0, 1, 0.5), y = c(-0.02, -0.02, top + 0.02), label = dimnames, gp = gpar(fontsize = 12)) } if (dimnames_position == "edge") { shift <- eps * if (labels == "outside") 8 else 0 grid.text(x = 0.25 - 2 * eps - shift, y = 0.5 * top + shift, label = dimnames[2], rot = dimnames_rot[2], gp = gpar(col = dimnames_color)) grid.text(x = 0.75 + 3 * eps + shift, y = 0.5 * top + shift, label = dimnames[1], rot = dimnames_rot[1], gp = gpar(col = dimnames_color)) grid.text(x = 0.5, y = -0.02 - shift, label = dimnames[3], rot = dimnames_rot[3], gp = gpar(col = dimnames_color)) } ## grid if (is.character(grid)) for (i in 1:4 * 0.2) { ## a - axis grid.lines(c(1 - i , (1 - i) / 2), c(0, 1 - i) * top, gp = gpar(lty = grid, col = grid_color)) ## b - axis grid.lines(c(1 - i , 1 - i + i / 2), c(0, i) * top, gp = gpar(lty = grid, col = grid_color)) ## c - axis grid.lines(c(i / 2, 1 - i + i/2), c(i, i) * top, gp = gpar(lty = grid, col = grid_color)) ## grid labels if (labels == "inside") { grid.text(x = (1 - i) * 3 / 4 - eps, y = (1 - i) / 2 * top, label = i * scale, gp = gpar(col = labels_color), rot = labels_rot[1]) grid.text(x = 1 - i + i / 4 + eps, y = i / 2 * top - eps, label = (1 - i) * scale, gp = gpar(col = labels_color), rot = labels_rot[2]) grid.text(x = 0.5, y = i * top + eps, label = i * scale, gp = gpar(col = labels_color), rot = labels_rot[3]) } if (labels == "outside") { grid.text(x = (1 - i) / 2 - 6 * eps, y = (1 - i) * top, label = (1 - i) * scale, rot = labels_rot[3], gp = gpar(col = labels_color)) grid.text(x = 1 - (1 - i) / 2 + 3 * eps, y = (1 - i) * top + 5 * eps, label = i * scale, rot = labels_rot[2], gp = gpar(col = labels_color)) grid.text(x = i + eps, y = -0.05, label = (1 - i) * scale, vjust = 1, rot = labels_rot[1], gp = gpar(col = labels_color)) } } ## plot points xp <- x[,2] + x[,3] / 2 yp <- x[,3] * top size = unit(if(prop_size) prop_size * (s / max(s)) else cex, "lines") grid.points(xp, yp, pch = pch, gp = gpar(col = col), default.units = "snpc", size = size, ...) ## plot if (!is.null(id)) grid.text(x = xp, y = unit(yp - 0.015, "snpc") - 0.5 * size, label = as.character(id), just = id_just, gp = gpar(col = id_color, cex = cex)) ## cleanup if(pop) popViewport(2) else upViewport(2) if (return_grob) invisible(grid.grab()) else invisible(NULL) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/ternaryplot.R
tile <- function(x, ...) UseMethod("tile") tile.formula <- function(formula, data = NULL, ..., main = NULL, sub = NULL, subset = NULL, na.action = NULL) { if (is.logical(main) && main) main <- deparse(substitute(data)) else if (is.logical(sub) && sub) sub <- deparse(substitute(data)) m <- match.call(expand.dots = FALSE) edata <- eval(m$data, parent.frame()) fstr <- strsplit(paste(deparse(formula), collapse = ""), "~") vars <- strsplit(strsplit(gsub(" ", "", fstr[[1]][2]), "\\|")[[1]], "\\+") varnames <- vars[[1]] dep <- gsub(" ", "", fstr[[1]][1]) if (!dep %in% c("","Freq")) { if (all(varnames == ".")) { varnames <- if (is.data.frame(data)) colnames(data) else names(dimnames(as.table(data))) varnames <- varnames[-which(varnames %in% dep)] } varnames <- c(varnames, dep) } if (inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) { dat <- as.table(data) if(all(varnames != ".")) { ind <- match(varnames, names(dimnames(dat))) if (any(is.na(ind))) stop(paste("Can't find", paste(varnames[is.na(ind)], collapse=" / "), "in", deparse(substitute(data)))) dat <- margin.table(dat, ind) } tile.default(dat, main = main, sub = sub, ...) } else { m <- m[c(1, match(c("formula", "data", "subset", "na.action"), names(m), 0))] m[[1]] <- as.name("xtabs") m$formula <- formula(paste(if("Freq" %in% colnames(data)) "Freq", "~", paste(varnames, collapse = "+"))) tab <- eval(m, parent.frame()) tile.default(tab, main = main, sub = sub, ...) } } tile.default <- function(x, tile_type = c("area", "squaredarea", "height", "width"), halign = c("left", "center", "right"), valign = c("bottom", "center", "top"), split_vertical = NULL, shade = FALSE, spacing = spacing_equal(unit(1, "lines")), set_labels = NULL, margins = unit(3, "lines"), keep_aspect_ratio = FALSE, legend = NULL, legend_width = NULL, squared_tiles = TRUE, main = NULL, sub = NULL, ...) { ## argument handling if (is.logical(main) && main) main <- deparse(substitute(x)) else if (is.logical(sub) && sub) sub <- deparse(substitute(x)) tile_type <- match.arg(tile_type) halign <- match.arg(halign) valign <- match.arg(valign) x <- as.table(x) dl <- length(d <- dim(x)) ## determine starting positions xpos <- 1 - (halign == "left") - 0.5 * (halign == "center") ypos <- 1 - (valign == "bottom") - 0.5 * (valign == "center") ## heuristic to adjust right/bottom margin to obtain squared tiles ## FIXME: better push another viewport? if (squared_tiles) { ## splitting argument if (is.structable(x) && is.null(split_vertical)) split_vertical <- attr(x, "split_vertical") if (is.null(split_vertical)) split_vertical <- FALSE if (length(split_vertical) == 1) split_vertical <- rep(c(split_vertical, !split_vertical), length.out = dl) if (length(split_vertical) < dl) split_vertical <- rep(split_vertical, length.out = dl) ## compute resulting dimnension dflat <- dim(unclass(structable(x, split_vertical = split_vertical))) ## adjust margins spacing <- spacing(d) delta <- abs(dflat[1] - dflat[2]) fac <- delta / max(dflat) un <- unit(fac, "npc") - unit(fac * 5 / convertWidth(spacing[[1]], "lines", valueOnly=TRUE), "lines") leg <- if (shade) { if (is.null(legend_width)) unit(5, "lines") else legend_width } else unit(0, "npc") if (dflat[1] < dflat[2]) margins <- margins + unit.c(unit(0, "npc"), unit(0, "npc"), un + leg, unit(0, "npc")) if (dflat[1] > dflat[2]) margins <- margins + unit.c(unit(0, "npc"), un - leg, unit(0, "npc"), unit(0, "npc")) if (dflat[1] == dflat[2]) margins <- margins + unit.c(unit(0, "npc"), unit(0, "npc"), leg, unit(0, "npc")) } ## create dummy labels if some are duplicated ## and set the labels via set_labels dn <- dimnames(x) if (any(unlist(lapply(dn, duplicated)))) { dimnames(x) <- lapply(dn, seq_along) if (is.null(set_labels)) set_labels <- lapply(dn, function(i) structure(i, names = seq(i))) } ## workhorse function creating bars panelfun <- function(residuals, observed, expected, index, gp, name) { xprop <- expected / max(expected) if (tile_type == "height") grid.rect(x = xpos, y = ypos, height = xprop[t(index)], width = 1, gp = gp, just = c(halign, valign), name = name) else if (tile_type == "width") grid.rect(x = xpos, y = ypos, width = xprop[t(index)], height = 1, gp = gp, just = c(halign, valign), name = name) else if (tile_type == "area") grid.rect(x = xpos, y = ypos, width = sqrt(xprop[t(index)]), height = sqrt(xprop[t(index)]), gp = gp, just = c(halign, valign), name = name) else grid.rect(x = xpos, y = ypos, width = xprop[t(index)], height = xprop[t(index)], gp = gp, just = c(halign, valign), name = name) } mycore <- function(residuals, observed, expected = NULL, spacing, gp, split_vertical, prefix = "") { struc_mosaic(panel = panelfun)(residuals, array(1, dim = d, dimnames = dimnames(observed)), expected = observed, spacing, gp, split_vertical, prefix) } strucplot(x, core = mycore, spacing = spacing, keep_aspect_ratio = keep_aspect_ratio, margins = margins, shade = shade, legend = legend, legend_width = legend_width, main = main, sub = sub, set_labels = set_labels, ...) }
/scratch/gouwar.j/cran-all/cranData/vcd/R/tile.R
remove_trailing_comma <- function(x) sub(",$", "", x)
/scratch/gouwar.j/cran-all/cranData/vcd/R/utils.R
woolf_test <- function(x) { DNAME <- deparse(substitute(x)) if (any(x == 0)) x <- x + 1 / 2 k <- dim(x)[3] or <- apply(x, 3, function(x) (x[1,1] * x[2,2]) / (x[1,2] * x[2,1])) w <- apply(x, 3, function(x) 1 / sum(1 / x)) o <- log(or) e <- weighted.mean(log(or), w) STATISTIC <- sum(w * (o - e)^2) PARAMETER <- k - 1 PVAL <- 1 - pchisq(STATISTIC, PARAMETER) METHOD <- "Woolf-test on Homogeneity of Odds Ratios (no 3-Way assoc.)" names(STATISTIC) <- "X-squared" names(PARAMETER) <- "df" structure(list(statistic = STATISTIC, parameter = PARAMETER, p.value = PVAL, method = METHOD, data.name = DNAME, observed = o, expected = e), class = "htest") }
/scratch/gouwar.j/cran-all/cranData/vcd/R/woolf_test.R
################################################# ## Fitting and Graphing Discrete Distributions ## ################################################# data(HorseKicks) barplot(HorseKicks, col = 2, xlab = "Number of Deaths", ylab = "Number of Corps-Years", main = "Deaths by Horse Kicks") data(Federalist) barplot(Federalist, col = 2, xlab = "Occurrences of 'may'", ylab = "Number of Blocks of Text", main = "'may' in Federalist papers") data(WomenQueue) barplot(WomenQueue, col = 2, xlab = "Number of women", ylab = "Number of queues", main = "Women in queues of length 10") data(WeldonDice) barplot(WeldonDice, names = c(names(WeldonDice)[-11], "10+"), col = 2, xlab = "Number of 5s and 6s", ylab = "Frequency", main = "Weldon's dice data") data(Butterfly) barplot(Butterfly, col = 2, xlab = "Number of individuals", ylab = "Number of Species", main = "Butterfly species im Malaya") ############################ ## Binomial distributions ## ############################ par(mfrow = c(1,2)) barplot(dbinom(0:10, p = 0.15, size = 10), names = 0:10, col = grey(0.7), main = "p = 0.15", ylim = c(0,0.35)) barplot(dbinom(0:10, p = 0.35, size = 10), names = 0:10, col = grey(0.7), main = "p = 0.35", ylim = c(0,0.35)) par(mfrow = c(1,1)) mtext("Binomial distributions", line = 2, cex = 1.5) plot(0:10, dbinom(0:10, p = 0.15, size = 10), type = "b", ylab = "Density", ylim = c(0, 0.4), main = "Binomial distributions, N = 10", pch = 19) lines(0:10, dbinom(0:10, p = 0.35, size = 10), type = "b", col = 2, pch = 19) lines(0:10, dbinom(0:10, p = 0.55, size = 10), type = "b", col = 4, pch = 19) lines(0:10, dbinom(0:10, p = 0.75, size = 10), type = "b", col = 3, pch = 19) legend(3, 0.4, c("p", "0.15", "0.35", "0.55", "0.75"), lty = rep(1,5), col = c(0,1,2,4,3), bty = "n") ########################### ## Poisson distributions ## ########################### par(mfrow = c(1,2)) dummy <- barplot(dpois(0:12, 2), names = 0:12, col = grey(0.7), ylim = c(0,0.3), main = expression(lambda == 2)) abline(v = dummy[3], col = 2) diff <- (dummy[3] - dummy[2]) * sqrt(2)/2 lines(c(dummy[3] - diff, dummy[3] + diff), c(0.3, 0.3), col = 2) dummy <- barplot(dpois(0:12, 5), names = 0:12, col = grey(0.7), ylim = c(0,0.3), main = expression(lambda == 5)) abline(v = dummy[6], col = 2) diff <- (dummy[6] - dummy[5]) * sqrt(5)/2 lines(c(dummy[6] - diff, dummy[6] + diff), c(0.3, 0.3), col = 2) par(mfrow = c(1,1)) mtext("Poisson distributions", line = 2, cex = 1.5) ##################################### ## Negative binomial distributions ## ##################################### nbplot <- function(p = 0.2, size = 2, ylim = c(0, 0.2)) { plot(0:20, dnbinom(0:20, p = p, size = size), type = "h", col = grey(0.7), xlab = "Number of failures (k)", ylab = "Density", ylim = ylim, yaxs = "i", bty = "L") nb.mean <- size * (1-p)/p nb.sd <- sqrt(nb.mean/p) abline(v = nb.mean, col = 2) lines(nb.mean + c(-nb.sd, nb.sd), c(0.01, 0.01), col = 2) legend(14, 0.2, c(paste("p = ", p), paste("n = ", size)), bty = "n") } par(mfrow = c(3,2)) nbplot() nbplot(size = 4) nbplot(p = 0.3) nbplot(p = 0.3, size = 4) nbplot(p = 0.4, size = 2) nbplot(p = 0.4, size = 4) par(mfrow = c(1,1)) mtext("Negative binomial distributions for the number of trials to observe n = 2 or n = 4 successes", line = 3) ##################### ## Goodness of fit ## ##################### p <- weighted.mean(as.numeric(names(HorseKicks)), HorseKicks) p.hat <- dpois(0:4, p) expected <- sum(HorseKicks) * p.hat chi2 <- sum((HorseKicks - expected)^2/expected) pchisq(chi2, df = 3, lower = FALSE) ## or: HK.fit <- goodfit(HorseKicks) summary(HK.fit) ## Are the dice fair? p.hyp <- 1/3 p.hat <- dbinom(0:12, prob = p.hyp, size = 12) expected <- sum(WeldonDice) * p.hat expected <- c(expected[1:10], sum(expected[11:13])) chi2 <- sum((WeldonDice - expected)^2/expected) G2 <- 2*sum(WeldonDice*log(WeldonDice/expected)) pchisq(chi2, df = 10, lower = FALSE) ## Are the data from a binomial distribution? p <- weighted.mean(as.numeric(names(WeldonDice))/12, WeldonDice) p.hat <- dbinom(0:12, prob = p, size = 12) expected <- sum(WeldonDice) * p.hat expected <- c(expected[1:10], sum(expected[11:13])) chi2 <- sum((WeldonDice - expected)^2/expected) G2 <- 2*sum(WeldonDice*log(WeldonDice/expected)) pchisq(chi2, df = 9, lower = FALSE) ## or: WD.fit1 <- goodfit(WeldonDice, type = "binomial", par = list(prob = 1/3, size = 12)) WD.fit1$fitted[11] <- sum(predict(WD.fit1, newcount = 10:12)) WD.fit2 <- goodfit(WeldonDice, type = "binomial", par = list(size = 12), method = "MinChisq") summary(WD.fit1) summary(WD.fit2) F.fit1 <- goodfit(Federalist) F.fit2 <- goodfit(Federalist, type = "nbinomial") summary(F.fit1) par(mfrow = c(2,2)) plot(F.fit1, scale = "raw", type = "standing") plot(F.fit1, type = "standing") plot(F.fit1) plot(F.fit1, type = "deviation") par(mfrow = c(1,1)) plot(F.fit2, type = "deviation") summary(F.fit2) data(Saxony) S.fit <- goodfit(Saxony, type = "binomial", par = list(size = 12)) summary(S.fit) plot(S.fit) ############### ## Ord plots ## ############### par(mfrow = c(2,2)) Ord_plot(HorseKicks, main = "Death by horse kicks") Ord_plot(Federalist, main = "Instances of 'may' in Federalist papers") Ord_plot(Butterfly, main = "Butterfly species collected in Malaya") Ord_plot(WomenQueue, main = "Women in queues of length 10") par(mfrow = c(1,1)) ############### ## Distplots ## ############### distplot(HorseKicks, type = "poisson") distplot(HorseKicks, type = "poisson", lambda = 0.61) distplot(Federalist, type = "poisson") distplot(Federalist, type = "nbinomial") distplot(Saxony, type = "binomial", size = 12)
/scratch/gouwar.j/cran-all/cranData/vcd/demo/discrete.R
if(require("tcltk")) { hue <- tclVar("hue") chroma <- tclVar("chroma") luminance <- tclVar("luminance") fixup <- tclVar("fixup") hue <- tclVar(230) hue.sav <- 230 chroma <- tclVar(55) chroma.sav <- 55 luminance <- tclVar(75) luminance.sav <- 75 fixup <- tclVar(FALSE) replot <- function(...) { hue.sav <- my.h <- as.numeric(tclvalue(hue)) chroma.sav <- my.c <- as.numeric(tclvalue(chroma)) luminance.sav <- my.l <- as.numeric(tclvalue(luminance)) my.fixup <- as.logical(as.numeric(tclvalue(fixup))) barplot(1, col = hcl2hex(my.h, my.c, my.l, fixup = my.fixup), axes = FALSE) } replot.maybe <- function(...) { if(!((as.numeric(tclvalue(hue)) == hue.sav) && (as.numeric(tclvalue(chroma)) == chroma.sav) && (as.numeric(tclvalue(luminance)) == luminance.sav))) replot() } base <- tktoplevel() tkwm.title(base, "HCL Colors") spec.frm <- tkframe(base, borderwidth = 2) hue.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) chroma.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) luminance.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) fixup.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) tkpack(tklabel(hue.frm, text = "Hue")) tkpack(tkscale(hue.frm, command = replot.maybe, from = 0, to = 360, showvalue = TRUE, variable = hue, resolution = 1, orient = "horiz")) tkpack(tklabel(chroma.frm, text = "Chroma")) tkpack(tkscale(chroma.frm, command = replot.maybe, from = 0, to = 100, showvalue = TRUE, variable = chroma, resolution = 5, orient = "horiz")) tkpack(tklabel(luminance.frm, text = "Luminance")) tkpack(tkscale(luminance.frm, command = replot.maybe, from = 0, to = 100, showvalue = TRUE, variable = luminance, resolution = 5, orient = "horiz")) tkpack(tklabel(fixup.frm, text="Fixup")) for (i in c("TRUE", "FALSE") ) { tmp <- tkradiobutton(fixup.frm, command = replot, text = i, value = as.logical(i), variable = fixup) tkpack(tmp, anchor="w") } tkpack(hue.frm, chroma.frm, luminance.frm, fixup.frm, fill="x") ## Bottom frame on base: q.but <- tkbutton(base, text = "Quit", command = function() tkdestroy(base)) tkpack(spec.frm, q.but) replot() }
/scratch/gouwar.j/cran-all/cranData/vcd/demo/hcl.R
if(require("tcltk")) { hue <- tclVar("hue") luminance <- tclVar("luminance") saturation <- tclVar("saturation") hue <- tclVar(0) hue.sav <- 0 luminance <- tclVar(0.5) luminance.sav <- 0.5 saturation <- tclVar(1) saturation.sav <- 1 replot <- function(...) { hue.sav <- my.h <- as.numeric(tclvalue(hue)) saturation.sav <- my.s <- as.numeric(tclvalue(saturation)) luminance.sav <- my.l <- as.numeric(tclvalue(luminance)) barplot(1, col = hls(my.h, my.l, my.s), axes = FALSE) } replot.maybe <- function(...) { if(!((as.numeric(tclvalue(hue)) == hue.sav) && (as.numeric(tclvalue(saturation)) == saturation.sav) && (as.numeric(tclvalue(luminance)) == luminance.sav))) replot() } base <- tktoplevel() tkwm.title(base, "HLS Colors") spec.frm <- tkframe(base, borderwidth = 2) hue.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) saturation.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) luminance.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) tkpack(tklabel(hue.frm, text = "Hue")) tkpack(tkscale(hue.frm, command = replot.maybe, from = 0, to = 1, showvalue = TRUE, variable = hue, resolution = 0.01, orient = "horiz")) tkpack(tklabel(luminance.frm, text = "Luminance")) tkpack(tkscale(luminance.frm, command = replot.maybe, from = 0, to = 1, showvalue = TRUE, variable = luminance, resolution = 0.01, orient = "horiz")) tkpack(tklabel(saturation.frm, text = "Saturation")) tkpack(tkscale(saturation.frm, command = replot.maybe, from = 0, to = 1, showvalue = TRUE, variable = saturation, resolution = 0.01, orient = "horiz")) tkpack(hue.frm, luminance.frm, saturation.frm, fill="x") ## Bottom frame on base: q.but <- tkbutton(base, text = "Quit", command = function() tkdestroy(base)) tkpack(spec.frm, q.but) replot() }
/scratch/gouwar.j/cran-all/cranData/vcd/demo/hls.R
if(require("tcltk")) { hue <- tclVar("hue") saturation <- tclVar("saturation") value <- tclVar("value") hue <- tclVar(0) hue.sav <- 0 saturation <- tclVar(1) saturation.sav <- 1 value <- tclVar(1) value.sav <- 1 replot <- function(...) { hue.sav <- my.h <- as.numeric(tclvalue(hue)) saturation.sav <- my.s <- as.numeric(tclvalue(saturation)) value.sav <- my.v <- as.numeric(tclvalue(value)) barplot(1, col = hsv(my.h, my.s, my.v), axes = FALSE) } replot.maybe <- function(...) { if(!((as.numeric(tclvalue(hue)) == hue.sav) && (as.numeric(tclvalue(saturation)) == saturation.sav) && (as.numeric(tclvalue(value)) == value.sav))) replot() } base <- tktoplevel() tkwm.title(base, "HSV Colors") spec.frm <- tkframe(base, borderwidth = 2) hue.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) saturation.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) value.frm <- tkframe(spec.frm, relief = "groove", borderwidth = 2) tkpack(tklabel(hue.frm, text = "Hue")) tkpack(tkscale(hue.frm, command = replot.maybe, from = 0, to = 1, showvalue = TRUE, variable = hue, resolution = 0.01, orient = "horiz")) tkpack(tklabel(saturation.frm, text = "Saturation")) tkpack(tkscale(saturation.frm, command = replot.maybe, from = 0, to = 1, showvalue = TRUE, variable = saturation, resolution = 0.01, orient = "horiz")) tkpack(tklabel(value.frm, text = "Value")) tkpack(tkscale(value.frm, command = replot.maybe, from = 0, to = 1, showvalue = TRUE, variable = value, resolution = 0.01, orient = "horiz")) tkpack(hue.frm, saturation.frm, value.frm, fill="x") ## Bottom frame on base: q.but <- tkbutton(base, text = "Quit", command = function() tkdestroy(base)) tkpack(spec.frm, q.but) replot() }
/scratch/gouwar.j/cran-all/cranData/vcd/demo/hsv.R
###################################################### #### ternary plot demo #### Task: plotting data point hulls in a ternary plot #### data provided by Manuel Dominguez-Rodrigo ###################################################### library(vcd) ## data humans=matrix(c(18,19,17,21,7,9,8,62,70,53,69,81,73,71,20,10,30,10,12,18,19), ncol=3) colnames(humans)=c("young", "adult", "old") lions=matrix(c(41,59,62,49,45,21,12,5,11,13,38,29,33,40,42), ncol=3) colnames(lions)=c("young", "adult", "old") site=matrix(c(9,12,15,11,70,62,69,68,21,26,16,21), ncol=3) colnames(site)=c("young", "adult", "old") humans=matrix(c(18,19,17,21,7,9,8,62,70,53,69,81,73,71,20,10,30,10,12,18,19), ncol=3) ## regular ternary plot data = rbind(humans, lions, site) count = c(nrow(humans), nrow(lions), nrow(site)) rownames(data) = rep(c("humans", "lions", "site"), count) cols = rep(c("red", "green", "blue"), count) ternaryplot(data, col = cols) ## now try to draw hull prop2xy <- function(x) { x <- as.matrix(x) x <- x / rowSums(x) xp <- x[,2] + x[,3] / 2 yp <- x[,3] * sqrt(3) / 2 cbind(x = xp, y = yp) } hullpoints <- function(x) { ind <- chull(x) ind <- c(ind, ind[1]) x[ind,] } drawhull <- function(data, color) { hp <- hullpoints(prop2xy(data)) grid.lines(hp[,"x"], hp[,"y"], gp = gpar(col = color)) } ## setup plot region without data points ternaryplot(data, col = NA, pop = FALSE) ## grab plot viewport downViewport("plot") ## now plot hulls drawhull(humans, "blue") drawhull(site, "red") drawhull(lions, "green")
/scratch/gouwar.j/cran-all/cranData/vcd/demo/hullternary.R
library(vcd) ## shape foo1 <- c(3, 7, 3, 1.5) foo2 <- c(2, 6.5, 1.5) foo <- outer(foo1/sum(foo1), foo2/sum(foo2), "*") ## color mondrian <- rep("#EAE6E3", 12) mondrian[1] <- "#DE1024" mondrian[3] <- "#FFD83B" mondrian[12] <- "#032349" ## plot ## best visualized with resized display, e.g. using: ## get(getOption("device"))(width = 4.9, height = 7.5) grid.newpage() grid.rect(gp = gpar(fill = 1)) mondrianMosaic <- function(x, fill) mosaic(x, gp = gpar(col = rep(0, length(fill)), fill = fill), legend = FALSE, margins = 0, newpage = FALSE, keep_aspect_ratio = FALSE) mondrianMosaic(foo, mondrian)
/scratch/gouwar.j/cran-all/cranData/vcd/demo/mondrian.R
##################### ## Mosaic Displays ## ##################### ######################### ## Hair Eye Color Data ## ######################### data(HairEyeColor) ## Basic Mosaic Display ## HairEye <- margin.table(HairEyeColor, c(1,2)) mosaic(HairEye, main = "Basic Mosaic Display of Hair Eye Color data") ## Hair Mosaic Display with Pearson residuals ## Hair <- margin.table(HairEyeColor,1) Hair mHair <- as.table(rep(mean(margin.table(HairEyeColor, 1)), 4)) names(mHair) <- names(Hair) mHair ## Pearson residuals from Equiprobability model ## resid <- (Hair - mHair) / sqrt(mHair) resid ## First Step in a Mosaic Display ## mosaic(Hair, residuals = resid, main = "Hair Color Proportions") ## Hair Eye Mosais Display with Pearson residuals ## mosaic(HairEye, main = " Hair Eye Color with Pearson residuals") ## Show Pearson Residuals ## (HairEye - loglin(HairEye, c(1, 2), fit = TRUE)$fit) / sqrt(loglin(HairEye, c(1, 2), fit = TRUE)$fit) ################### ## UKSoccer Data ## ################### data(UKSoccer) ## UKSoccer Mosaic Display ## mosaic(UKSoccer, main = "UK Soccer Scores") ############################### ## Repeat Victimization Data ## ############################### data(RepVict) ## mosaic(RepVict[-c(4, 7), -c(4, 7)], main = "Repeat Victimization Data") ################## ## 3-Way Tables ## ################## ## Hair Eye Sex Mosais Display with Pearson residuals ## mosaic(HairEyeColor, main = "Hair Eye Color Sex" ) mosaic(HairEyeColor, expected = ~ Hair * Eye + Sex, main = "Model: (Hair Eye) (Sex)" ) mosaic(HairEyeColor, expected = ~ Hair * Sex + Eye*Sex, main = "Model: (Hair Sex) (Eye Sex)") #################### ## Premarital Sex ## #################### data(PreSex) ## Mosaic display for Gender and Premarital Sexual Expirience ## ## (Gender Pre) ## mosaic(margin.table(PreSex, c(3, 4)), legend = FALSE, main = "Gender and Premarital Sex") ## (Gender Pre)(Extra) ## mosaic(margin.table(PreSex,c(2,3,4)), legend = FALSE, expected = ~ Gender * PremaritalSex + ExtramaritalSex , main = "(PreMaritalSex Gender) (Sex)") ## (Gender Pre Extra)(Marital) ## mosaic(PreSex, expected = ~ Gender * PremaritalSex * ExtramaritalSex + MaritalStatus, legend = FALSE, main = "(PreMarital ExtraMarital) (MaritalStatus)") ## (GPE)(PEM) ## mosaic(PreSex, expected = ~ Gender * PremaritalSex * ExtramaritalSex + MaritalStatus * PremaritalSex * ExtramaritalSex, legend = FALSE, main = "(G P E) (P E M)") ############################ ## Employment Status Data ## ############################ data(Employment) ## Employment Status ## # mosaic(Employment, # expected = ~ LayoffCause * EmploymentLength + EmploymentStatus, # main = "(Layoff Employment) + (EmployStatus)") # mosaic(Employment, # expected = ~ LayoffCause * EmploymentLength + # LayoffCause * EmploymentStatus, # main = "(Layoff EmpL) (Layoff EmplS)") # ## Closure ## # mosaic(Employment[,,1], main = "Layoff : Closure") # ## Replaced ## # mosaic(Employment[,,2], main = "Layoff : Replaced") ##################### ## Mosaic Matrices ## ##################### data(UCBAdmissions) pairs(PreSex) pairs(UCBAdmissions) pairs(UCBAdmissions, type = "conditional") pairs(UCBAdmissions, type = "pairwise", gp = shading_max)
/scratch/gouwar.j/cran-all/cranData/vcd/demo/mosaic.R
data("Titanic") data("UCBAdmissions") data("HairEyeColor") data("PreSex") mosaic(Titanic) mosaic(Titanic, shade = TRUE) mosaic(~ Sex + Class, data = Titanic, shade = TRUE) mosaic(~ Sex + Class + Survived, data = Titanic, shade = TRUE) mosaic(~ PremaritalSex + ExtramaritalSex | MaritalStatus + Gender, data = PreSex) mosaic(~ PremaritalSex + ExtramaritalSex | MaritalStatus + Gender, data = PreSex, labeling = labeling_conditional(abbreviate_varnames = TRUE)) mosaic(Titanic, spacing = spacing_increase()) mosaic(Titanic, spacing = spacing_equal()) mosaic(Titanic, labeling = labeling_border()) mosaic(Titanic, labeling = labeling_cells()) mosaic(Titanic, labeling = labeling_cells(abbreviate_labels = TRUE)) mosaic(Titanic, labeling = labeling_cells(abbreviate_varnames = TRUE)) mosaic(Titanic, labeling = labeling_cells(abbreviate_varnames = TRUE, abbreviate_labels = TRUE)) mosaic(Titanic, labeling = labeling_border(abbreviate = TRUE)) mosaic(Titanic, labeling = labeling_border(abbreviate = c(Survived = TRUE))) mosaic(Titanic, labeling = labeling_border(rot_labels = c(bottom = 45))) mosaic(Titanic, labeling = labeling_border(tl_labels = TRUE)) mosaic(Titanic, labeling = labeling_border(tl_labels = TRUE, tl_varnames = FALSE)) mosaic(Titanic, labeling = labeling_border(tl_labels = TRUE, tl_varnames = c(TRUE,TRUE,FALSE,FALSE), boxes = TRUE)) mosaic(Titanic, labeling = labeling_cboxed()) mosaic(Titanic, labeling = labeling_lboxed()) mosaic(Titanic, labeling = labeling_left()) mosaic(Titanic, labeling = labeling_list(), mar = c(2,2,4,2)) mosaic(Titanic, labeling = labeling_border(rep = FALSE)) mosaic(Titanic, labeling = labeling_border(labbl_varnames = c(TRUE,TRUE,FALSE,FALSE))) mosaic(~ Gender + Admit | Dept, data = UCBAdmissions, labeling = labeling_conditional(labels_varnames = TRUE, varnames = FALSE), keep_aspect_ratio = FALSE, split_vertical = c(Dept = TRUE)) doubledecker(Titanic) assoc(Hair ~ Eye, data = HairEyeColor) assoc(Hair ~ Eye, data = HairEyeColor, compress = FALSE) assoc(HairEyeColor, labeling = labeling_lboxed()) pairs(Titanic, shade = TRUE) pairs(Titanic, panel_upper = pairs_assoc, shade = TRUE)
/scratch/gouwar.j/cran-all/cranData/vcd/demo/strucplot.R
##################### ## Fourfold tables ## ##################### ### Berkeley Admission Data ### ############################### data(UCBAdmissions) ## unstratified ### no margin is standardized x <- margin.table(UCBAdmissions, 2:1) fourfold(x, std = "i", extended = FALSE) ### std. for gender fourfold(x, margin = 1, extended = FALSE) ### std. for both fourfold(x, extended = FALSE) ## stratified fourfold(UCBAdmissions, extended = FALSE) fourfold(UCBAdmissions) ## extended plots ## using cotabplot cotabplot(UCBAdmissions, panel = function(x, condlevels, ...) fourfold(co_table(x, names(condlevels))[[paste(condlevels, collapse = ".")]], newpage = F, return_grob = FALSE, ...) ) ### Coal Miners Lung Data ### ############################# data(CoalMiners) ## Fourfold display, both margins equated fourfold(CoalMiners, mfcol = c(3,3)) ## Log Odds Ratio Plot data(CoalMiners, package = "vcd") lor_CM <- loddsratio(CoalMiners) plot(lor_CM) lor_CM_df <- as.data.frame(lor_CM) # fit linear models using WLS age <- seq(20, 60, by = 5) lmod <- lm(LOR ~ age, weights = 1 / ASE^2, data = lor_CM_df) grid.lines(age, fitted(lmod), gp = gpar(col = "blue")) qmod <- lm(LOR ~ poly(age, 2), weights = 1 / ASE^2, data = lor_CM_df) grid.lines(age, fitted(qmod), gp = gpar(col = "red")) ## Fourfold display, strata equated fourfold(CoalMiners, std = "ind.max", mfcol = c(3,3)) #################### ## Sieve Diagrams ## #################### ### Hair Eye Color ### ###################### data(HairEyeColor) ## aggregate over `sex': (tab <- margin.table(HairEyeColor, 1:2)) ## plot expected values: sieve(t(tab), sievetype = "expected", shade = TRUE) ## plot sieve diagram: sieve(t(tab), shade = TRUE) ### Visual Acuity ### ##################### data(VisualAcuity) attach(VisualAcuity) sieve(Freq ~ right + left, data = VisualAcuity, subset = gender == "female", main = "Unaided distant vision data", labeling_args = list(set_varnames = c(left = "Left Eye Grade", right = "Right Eye Grade")), shade = TRUE ) detach(VisualAcuity) ### Berkeley Admission ### ########################## ## -> Larger tables: e.g., Cross factors ### Cross Gender and Admission data(UCBAdmissions) (tab <- xtabs(Freq ~ Dept + I(Gender : Admit), data = UCBAdmissions)) sieve(tab, labeling_args = list(set_varnames = c("I(Gender:Admit)" = "Gender:Admission", Dept = "Department")), main = "Berkeley Admissions Data", shade = TRUE ) ## or use extended sieve plots: sieve(UCBAdmissions, shade = TRUE) ###################### ## Association Plot ## ###################### ### Hair Eye Color ### ###################### data(HairEyeColor) assoc(margin.table(HairEyeColor, 1:2), labeling_args = list(set_varnames = c(Hair = "Hair Color", Eye = "Eye Color")), main = "Association Plot") #################### ## Agreement Plot ## #################### ### Sexual Fun ### ################## data(SexualFun) ## Kappa statistics Kappa(SexualFun) ## Agreement Chart agreementplot(t(SexualFun), weights = 1) ## Partial Agreement Chart and B-Statistics (agreementplot(t(SexualFun), xlab = "Husband's Rating", ylab = "Wife's Rating", main = "Husband's and Wife's Sexual Fun") ) ### MS Diagnosis data ### ######################### data(MSPatients) ## use e.g., X11(width = 12), or expand graphics device agreementplot(t(MSPatients[,,1]), main = "Winnipeg Patients") agreementplot(t(MSPatients[,,2]), main = "New Orleans Patients") ################## ## Ternary Plot ## ################## ### sample data ### ################### (x <- rbind(c(A=10,B=10,C=80), c(40,30,30), c(20,60,20) ) ) ternaryplot(x, cex = 2, col = c("black", "blue", "red"), coordinates = TRUE ) ### Arthritis Treatment Data ### ################################ data(Arthritis) ## Build table by crossing Treatment and Sex (tab <- as.table(xtabs(~ I(Sex:Treatment) + Improved, data = Arthritis))) ## Mark groups col <- c("red", "red", "blue", "blue") pch <- c(1, 19, 1, 19) ## plot ternaryplot( tab, col = col, pch = pch, cex = 2, bg = "lightgray", grid_color = "white", labels_color = "white", main = "Arthritits Treatment Data" ) ## legend grid_legend(0.8, 0.7, pch, col, rownames(tab), title = "GROUP") ### Baseball Hitters Data ### ############################# data(Hitters) attach(Hitters) colors <- c("black","red","green","blue","red","black","blue") pch <- substr(levels(Positions), 1, 1) ternaryplot( Hitters[,2:4], pch = as.character(Positions), col = colors[as.numeric(Positions)], main = "Baseball Hitters Data" ) grid_legend(0.8, 0.9, pch, colors, levels(Positions), title = "POSITION(S)") detach(Hitters) ### Lifeboats on the Titanic ### ################################ data(Lifeboats) attach(Lifeboats) ternaryplot( Lifeboats[,4:6], pch = ifelse(side=="Port", 1, 19), col = ifelse(side=="Port", "red", "blue"), id = ifelse(men/total > 0.1, as.character(boat), NA), dimnames_position = "edge", dimnames = c("Men of Crew", "Men passengers", "Women and Children"), main = "Lifeboats on the Titanic" ) grid_legend(0.8, 0.9, c(1, 19), c("red", "blue"), c("Port", "Starboard"), title = "SIDE") ## Load against time for Port/Starboard boats plot(launch, total, pch = ifelse(side == "Port", 1, 19), col = ifelse(side == "Port", "red", "darkblue"), xlab = "Launch Time", ylab = "Total loaded", main = "Lifeboats on the Titanic" ) legend(as.POSIXct("1912-04-15 01:48:00"), 70, legend = c("SIDE","Port","Starboard"), pch = c(NA, 1, 19), col = c(NA, "red", "darkblue") ) text(as.POSIXct(launch), total, labels = as.character(boat), pos = 3, offset = 0.3 ) abline(lm(total ~ as.POSIXct(launch), subset = side == "Port"), col = "red") abline(lm(total ~ as.POSIXct(launch), subset = side == "Starboard"), col = "darkblue") detach(Lifeboats)
/scratch/gouwar.j/cran-all/cranData/vcd/demo/twoway.R
### R code from vignette source 'residual-shadings.Rnw' ################################################### ### code chunk number 1: preliminaries ################################################### library("grid") library("vcd") rseed <- 1071 ################################################### ### code chunk number 2: Arthritis-data ################################################### data("Arthritis", package = "vcd") (art <- xtabs(~ Treatment + Improved, data = Arthritis, subset = Sex == "Female")) ################################################### ### code chunk number 3: Arthritis-classic (eval = FALSE) ################################################### ## mosaic(art) ## assoc(art) ################################################### ### code chunk number 4: Arthritis-classic1 ################################################### grid.newpage() pushViewport(viewport(layout = grid.layout(1, 2))) pushViewport(viewport(layout.pos.col=1, layout.pos.row=1)) mosaic(art, newpage = FALSE, margins = c(2.5, 4, 2.5, 3)) popViewport() pushViewport(viewport(layout.pos.col=2, layout.pos.row=1)) assoc(art, newpage = FALSE, margins = c(5, 2, 5, 4)) popViewport(2) ################################################### ### code chunk number 5: Arthritis-max ################################################### set.seed(rseed) (art_max <- coindep_test(art, n = 5000)) ################################################### ### code chunk number 6: Arthritis-sumsq ################################################### ss <- function(x) sum(x^2) set.seed(rseed) coindep_test(art, n = 5000, indepfun = ss) ################################################### ### code chunk number 7: Arthritis-extended (eval = FALSE) ################################################### ## mosaic(art, gp = shading_Friendly(lty = 1, eps = NULL)) ## mosaic(art, gp = shading_hsv, gp_args = list( ## interpolate = art_max$qdist(c(0.9, 0.99)), p.value = art_max$p.value)) ## set.seed(rseed) ## mosaic(art, gp = shading_max, gp_args = list(n = 5000)) ################################################### ### code chunk number 8: pistonrings-data ################################################### data("pistonrings", package = "HSAUR3") pistonrings ################################################### ### code chunk number 9: shadings ################################################### mymar <- c(1.5, 0.5, 0.5, 2.5) grid.newpage() pushViewport(viewport(layout = grid.layout(2, 3))) pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 1)) mosaic(art, margins = mymar, newpage = FALSE, gp = shading_Friendly(lty = 1, eps = NULL)) popViewport() pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 2)) mosaic(art, gp = shading_hsv, margins = mymar, newpage = FALSE, gp_args = list(interpolate = art_max$qdist(c(0.9, 0.99)), p.value = art_max$p.value)) popViewport() pushViewport(viewport(layout.pos.row = 1, layout.pos.col = 3)) set.seed(rseed) mosaic(art, gp = shading_max, margins = mymar, newpage = FALSE, gp_args = list(n = 5000)) popViewport() pushViewport(viewport(layout.pos.row = 2, layout.pos.col = 1)) mosaic(pistonrings, margins = mymar, newpage = FALSE, gp = shading_Friendly(lty = 1, eps = NULL, interpolate = c(1, 1.5))) popViewport() pushViewport(viewport(layout.pos.row = 2, layout.pos.col = 2)) mosaic(pistonrings, gp = shading_hsv, margins = mymar, newpage = FALSE, gp_args = list(p.value = 0.069, interpolate = c(1, 1.5))) popViewport() pushViewport(viewport(layout.pos.row = 2, layout.pos.col = 3)) mosaic(pistonrings, gp = shading_hcl, margins = mymar, newpage = FALSE, gp_args = list(p.value = 0.069, interpolate = c(1, 1.5))) popViewport(2) ################################################### ### code chunk number 10: pistonrings-inference ################################################### set.seed(rseed) coindep_test(pistonrings, n = 5000) set.seed(rseed) (pring_ss <- coindep_test(pistonrings, n = 5000, indepfun = ss)) ################################################### ### code chunk number 11: pistonrings-plot (eval = FALSE) ################################################### ## mosaic(pistonrings, gp = shading_Friendly(lty = 1, eps = NULL, interpolate = c(1, 1.5))) ## mosaic(pistonrings, gp = shading_hsv, gp_args = list(p.value = pring_ss$p.value, interpolate = c(1, 1.5))) ## mosaic(pistonrings, gp = shading_hcl, gp_args = list(p.value = pring_ss$p.value, interpolate = c(1, 1.5))) ################################################### ### code chunk number 12: alzheimer-data ################################################### data("alzheimer", package = "coin") alz <- xtabs(~ smoking + disease + gender, data = alzheimer) alz ################################################### ### code chunk number 13: alzheimer-plot1 ################################################### set.seed(rseed) cotabplot(~ smoking + disease | gender, data = alz, panel = cotab_coindep, panel_args = list(n = 5000)) ################################################### ### code chunk number 14: alzheimer-inference ################################################### set.seed(rseed) coindep_test(alz, 3, n = 5000) set.seed(rseed) coindep_test(alz, 3, n = 5000, indepfun = ss) set.seed(rseed) coindep_test(alz, 3, n = 5000, indepfun = ss, aggfun = sum) ################################################### ### code chunk number 15: alzheimer-plot (eval = FALSE) ################################################### ## set.seed(rseed) ## cotabplot(~ smoking + disease | gender, data = alz, panel = cotab_coindep, panel_args = list(n = 5000)) ################################################### ### code chunk number 16: Punishment-data ################################################### data("Punishment", package = "vcd") pun <- xtabs(Freq ~ memory + attitude + age + education, data = Punishment) ftable(pun, row.vars = c("age", "education", "memory")) ################################################### ### code chunk number 17: Punishment-assoc1 ################################################### set.seed(rseed) cotabplot(~ memory + attitude | age + education, data = pun, panel = cotab_coindep, n = 5000, type = "assoc", test = "maxchisq", interpolate = 1:2) ################################################### ### code chunk number 18: Punishment-mosaic1 ################################################### set.seed(rseed) cotabplot(~ memory + attitude | age + education, data = pun, panel = cotab_coindep, n = 5000, type = "mosaic", test = "maxchisq", interpolate = 1:2) ################################################### ### code chunk number 19: Punishment-inference ################################################### set.seed(rseed) coindep_test(pun, 3:4, n = 5000) set.seed(rseed) coindep_test(pun, 3:4, n = 5000, indepfun = ss) set.seed(rseed) coindep_test(pun, 3:4, n = 5000, indepfun = ss, aggfun = sum) ################################################### ### code chunk number 20: Punishment-assoc (eval = FALSE) ################################################### ## set.seed(rseed) ## cotabplot(~ memory + attitude | age + education, data = pun, panel = cotab_coindep, ## n = 5000, type = "assoc", test = "maxchisq", interpolate = 1:2) ################################################### ### code chunk number 21: Punishment-mosaic (eval = FALSE) ################################################### ## set.seed(rseed) ## cotabplot(~ memory + attitude | age + education, data = pun, panel = cotab_coindep, ## n = 5000, type = "mosaic", test = "maxchisq", interpolate = 1:2)
/scratch/gouwar.j/cran-all/cranData/vcd/inst/doc/residual-shadings.R
### R code from vignette source 'strucplot.Rnw' ################################################### ### code chunk number 1: preliminaries ################################################### set.seed(1071) library(grid) library(vcd) data(Titanic) data(HairEyeColor) data(PreSex) data(Arthritis) art <- xtabs(~Treatment + Improved, data = Arthritis) ################################################### ### code chunk number 2: Arthritis ################################################### mosaic(art, gp = shading_max, split_vertical = TRUE) ################################################### ### code chunk number 3: UCBAdmissions ################################################### cotabplot(UCBAdmissions, panel = cotab_coindep, shade = TRUE, legend = FALSE, type = "assoc") ################################################### ### code chunk number 4: PreSex ################################################### presextest <- coindep_test(PreSex, margin = c(1,4), indepfun = function(x) sum(x^2), n = 5000) mosaic(PreSex, condvars = c(1, 4), shade = TRUE, gp_args = list(p.value = presextest$p.value)) ################################################### ### code chunk number 5: Titanic ################################################### doubledecker(Survived ~ ., data = Titanic, labeling_args = list(set_varnames = c(Sex = "Gender"))) ################################################### ### code chunk number 6: vcdlayout ################################################### pushViewport(vcd:::vcdViewport(legend = T, mar =4)) seekViewport("main") grid.rect(gp = gpar(lwd = 3)) grid.text("main", gp = gpar(fontsize = 20)) seekViewport("sub") grid.rect(gp = gpar(lwd = 3)) grid.text("sub", gp = gpar(fontsize = 20)) seekViewport("plot") grid.rect(gp = gpar(lwd = 3)) grid.text("plot", gp = gpar(fontsize = 20)) seekViewport("legend") grid.text("legend", rot = 90, gp = gpar(fontsize = 20)) grid.rect(gp = gpar(lwd = 3)) seekViewport("legend_sub") grid.rect(gp = gpar(lwd = 3)) grid.text("[F]", gp = gpar(fontsize = 20)) seekViewport("legend_top") grid.rect(gp = gpar(lwd = 3)) grid.text("[E]", gp = gpar(fontsize = 20)) seekViewport("margin_top") grid.rect(gp = gpar(lwd = 3)) grid.text("margin_top", gp = gpar(fontsize = 20)) seekViewport("margin_bottom") grid.rect(gp = gpar(lwd = 3)) grid.text("margin_bottom", gp = gpar(fontsize = 20)) seekViewport("margin_right") grid.rect(gp = gpar(lwd = 3)) grid.text("margin_right", rot = 90, gp = gpar(fontsize = 20)) seekViewport("margin_left") grid.rect(gp = gpar(lwd = 3)) grid.text("margin_left", rot = 90, gp = gpar(fontsize = 20)) seekViewport("corner_top_left") grid.rect(gp = gpar(lwd = 3)) grid.text("[A]", gp = gpar(fontsize = 20)) seekViewport("corner_top_right") grid.rect(gp = gpar(lwd = 3)) grid.text("[B]", gp = gpar(fontsize = 20)) seekViewport("corner_bottom_left") grid.rect(gp = gpar(lwd = 3)) grid.text("[C]", gp = gpar(fontsize = 20)) seekViewport("corner_bottom_right") grid.rect(gp = gpar(lwd = 3)) grid.text("[D]", gp = gpar(fontsize = 20)) ################################################### ### code chunk number 7: structable ################################################### (HEC <- structable(Eye ~ Sex + Hair, data = HairEyeColor)) ################################################### ### code chunk number 8: Observed ################################################### mosaic(HEC) ################################################### ### code chunk number 9: Observed2 ################################################### mosaic(~ Sex + Eye + Hair, data = HairEyeColor) ################################################### ### code chunk number 10: Observedfig ################################################### mosaic(HEC) ################################################### ### code chunk number 11: Expected ################################################### mosaic(HEC, type = "expected") ################################################### ### code chunk number 12: Expectedfig ################################################### mosaic(HEC, type = "expected") ################################################### ### code chunk number 13: sieve ################################################### sieve(~ Sex + Eye + Hair, data = HEC, spacing = spacing_dimequal(c(2,0,0))) ################################################### ### code chunk number 14: sievefig ################################################### sieve(~ Sex + Eye + Hair, data = HEC, spacing = spacing_dimequal(c(2,0,0))) ################################################### ### code chunk number 15: Residuals ################################################### assoc(HEC, compress = FALSE) ################################################### ### code chunk number 16: Residualsfig ################################################### assoc(HEC, compress = FALSE) ################################################### ### code chunk number 17: strucplot.Rnw:592-593 ################################################### options(width=60) ################################################### ### code chunk number 18: split1 ################################################### mosaic(HEC, split_vertical = c(TRUE, FALSE, TRUE), labeling_args = list(abbreviate_labs = c(Eye = 3))) ################################################### ### code chunk number 19: strucplot.Rnw:601-602 ################################################### options(width=70) ################################################### ### code chunk number 20: splitfig ################################################### mosaic(HEC, split_vertical = c(TRUE, FALSE, TRUE), labeling_args = list(abbreviate_labs = c(Eye = 3))) ################################################### ### code chunk number 21: split2 ################################################### mosaic(HEC, direction = c("v","h","v")) ################################################### ### code chunk number 22: doubledecker1 ################################################### doubledecker(Titanic) ################################################### ### code chunk number 23: doubledecker2 ################################################### doubledecker(Survived ~ Class + Sex + Age, data = Titanic) ################################################### ### code chunk number 24: strucplot.Rnw:665-666 ################################################### options(width=75) ################################################### ### code chunk number 25: subsetting ################################################### (STD <- structable(~ Sex + Class + Age, data = Titanic[,,2:1,])) STD["Male",] STD["Male", c("1st","2nd","3rd")] ################################################### ### code chunk number 26: strucplot.Rnw:675-676 ################################################### options(width=70) ################################################### ### code chunk number 27: conditioning ################################################### STD[["Male",]] STD[[c("Male", "Adult"),]] STD[["Male","1st"]] ################################################### ### code chunk number 28: Variables1 ################################################### pushViewport(viewport(layout = grid.layout(ncol = 2))) ################################################### ### code chunk number 29: Variables2 ################################################### pushViewport(viewport(layout.pos.col = 1)) mosaic(STD[["Male"]], margins = c(left = 2.5, top = 2.5, 0), sub = "Male", newpage = FALSE) popViewport() ################################################### ### code chunk number 30: Variables3 ################################################### pushViewport(viewport(layout.pos.col = 2)) mosaic(STD[["Female"]], margins = c(top = 2.5, 0), sub = "Female", newpage = FALSE) popViewport(2) ################################################### ### code chunk number 31: Variablesfig ################################################### pushViewport(viewport(layout = grid.layout(ncol = 2))) pushViewport(viewport(layout.pos.col = 1)) mosaic(STD[["Male"]], margins = c(left = 2.5, top = 2.5, 0), sub = "Male", newpage = FALSE) popViewport() pushViewport(viewport(layout.pos.col = 2)) mosaic(STD[["Female"]], margins = c(top = 2.5, 0), sub = "Female", newpage = FALSE) popViewport(2) ################################################### ### code chunk number 32: cotabplot ################################################### cotabplot(~ Class + Age | Sex, data = STD, split_vertical = TRUE) ################################################### ### code chunk number 33: cotabplotfig ################################################### cotabplot(~ Class + Age | Sex, data = STD, split_vertical = TRUE) ################################################### ### code chunk number 34: Conditioning1 ################################################### mosaic(STD, condvars = "Sex", split_vertical = c(TRUE, TRUE, FALSE)) ################################################### ### code chunk number 35: Conditioning2 ################################################### mosaic(~ Class + Age | Sex, data = STD, split_vertical = c(TRUE, TRUE, FALSE)) ################################################### ### code chunk number 36: Conditioningfig ################################################### mosaic(~ Class + Age | Sex, data = STD, split_vertical = c(TRUE, TRUE, FALSE)) ################################################### ### code chunk number 37: pairs ################################################### pairs(STD, highlighting = 2, diag_panel = pairs_diagonal_mosaic, diag_panel_args = list(fill = grey.colors)) ################################################### ### code chunk number 38: pairsfig ################################################### pairs(STD, highlighting = 2, diag_panel = pairs_diagonal_mosaic, diag_panel_args = list(fill = grey.colors)) ################################################### ### code chunk number 39: viewportnames ################################################### mosaic(~ Hair + Eye, data = HEC, pop = FALSE) seekViewport("cell:Hair=Blond") grid.rect(gp = gpar(col = "red", lwd = 4)) seekViewport("cell:Hair=Blond,Eye=Blue") grid.circle(r = 0.2, gp = gpar(fill = "cyan")) ################################################### ### code chunk number 40: viewportnamesfig ################################################### mosaic(~ Hair + Eye, data = HEC, pop = FALSE) seekViewport("cell:Hair=Blond") grid.rect(gp = gpar(col = "red", lwd = 4)) seekViewport("cell:Hair=Blond,Eye=Blue") grid.circle(r = 0.2, gp = gpar(fill = "cyan")) ################################################### ### code chunk number 41: changeplot ################################################### assoc(Eye ~ Hair, data = HEC, pop = FALSE) getNames()[1:6] grid.edit("rect:Hair=Blond,Eye=Blue", gp = gpar(fill = "red")) ################################################### ### code chunk number 42: changeplotfig ################################################### x <- tab <- margin.table(HairEyeColor, 1:2) x[] <- "light gray" x["Blond","Blue"] <- "Red" assoc(tab, gp = gpar(fill = x)) ################################################### ### code chunk number 43: ucb ################################################### (ucb <- margin.table(UCBAdmissions, 1:2)) (fill_colors <- matrix(c("dark cyan","gray","gray","dark magenta"), ncol = 2)) mosaic(ucb, gp = gpar(fill = fill_colors, col = 0)) ################################################### ### code chunk number 44: ucbfig ################################################### (ucb <- margin.table(UCBAdmissions, 1:2)) (fill_colors <- matrix(c("dark cyan","gray","gray","dark magenta"), ncol = 2)) mosaic(ucb, gp = gpar(fill = fill_colors, col = 0)) ################################################### ### code chunk number 45: recycling ################################################### mosaic(Titanic, gp = gpar(fill = c("gray","dark magenta")), spacing = spacing_highlighting, labeling_args = list(abbreviate_labs = c(Age = 3), rep = c(Survived = FALSE)) ) ################################################### ### code chunk number 46: recyclingfig ################################################### mosaic(Titanic, gp = gpar(fill = c("gray","dark magenta")), spacing = spacing_highlighting, labeling_args = list(abbreviate_labs = c(Age = 3), rep = c(Survived = FALSE)) ) ################################################### ### code chunk number 47: shading1 ################################################### expected <- independence_table(ucb) (x <- (ucb - expected) / sqrt(expected)) (shading1_obj <- ifelse(x > 0, "royalblue4", "mediumorchid4")) mosaic(ucb, gp = gpar(fill = shading1_obj)) ################################################### ### code chunk number 48: shading1fig ################################################### expected <- independence_table(ucb) (x <- (ucb - expected) / sqrt(expected)) (shading1_obj <- ifelse(x > 0, "royalblue4", "mediumorchid4")) mosaic(ucb, gp = gpar(fill = shading1_obj)) ################################################### ### code chunk number 49: shading2 ################################################### shading2_fun <- function(x) gpar(fill = ifelse(x > 0, "royalblue4", "mediumorchid4")) ################################################### ### code chunk number 50: shading3 ################################################### mosaic(ucb, gp = shading2_fun) ################################################### ### code chunk number 51: shading3 ################################################### shading3a_fun <- function(col = c("royalblue4", "mediumorchid4")) { col <- rep(col, length.out = 2) function(x) gpar(fill = ifelse(x > 0, col[1], col[2])) } ################################################### ### code chunk number 52: shading4 ################################################### mosaic(ucb, gp = shading3a_fun(c("royalblue4","mediumorchid4"))) ################################################### ### code chunk number 53: shading4 ################################################### shading3b_fun <- function(observed = NULL, residuals = NULL, expected = NULL, df = NULL, col = c("royalblue4", "mediumorchid4")) { col <- rep(col, length.out = 2) function(x) gpar(fill = ifelse(x > 0, col[1], col[2])) } class(shading3b_fun) <- "grapcon_generator" ################################################### ### code chunk number 54: shading5 ################################################### mosaic(ucb, gp = shading3b_fun, gp_args = list(col = c("red","blue"))) ################################################### ### code chunk number 55: haireye1 ################################################### haireye <- margin.table(HairEyeColor, 1:2) mosaic(haireye, gp = shading_hsv) ################################################### ### code chunk number 56: haireye2 ################################################### mosaic(haireye, gp = shading_hcl) ################################################### ### code chunk number 57: haireye3 ################################################### mosaic(haireye, gp = shading_hcl, gp_args = list(h = c(130, 43), c = 100, l = c(90, 70))) ################################################### ### code chunk number 58: haireyefig1 ################################################### mosaic(haireye, gp = shading_hsv, margin = c(bottom = 1), keep_aspect_ratio = FALSE) ################################################### ### code chunk number 59: haireyefig2 ################################################### mosaic(haireye, gp = shading_hcl, margin = c(bottom = 1), keep_aspect_ratio = FALSE) ################################################### ### code chunk number 60: haireyefig3 ################################################### mosaic(haireye, gp = shading_hcl, margin = c(bottom = 1), gp_args = list(h = c(130, 43), c = 100, l = c(90, 70)), keep_aspect_ratio = FALSE) ################################################### ### code chunk number 61: interpolate ################################################### mosaic(haireye, shade = TRUE, gp_args = list(interpolate = 1:4)) ################################################### ### code chunk number 62: continuous1 ################################################### ipol <- function(x) pmin(x/4, 1) ################################################### ### code chunk number 63: continuous2 ################################################### mosaic(haireye, shade = TRUE, gp_args = list(interpolate = ipol), labeling_args = list(abbreviate_labs = c(Sex = TRUE))) ################################################### ### code chunk number 64: interpolatefig ################################################### pushViewport(viewport(layout = grid.layout(ncol = 2))) pushViewport(viewport(layout.pos.col = 1)) mosaic(haireye, gp_args = list(interpolate = 1:4), margin = c(right = 1), keep_aspect_ratio= FALSE,newpage = FALSE,legend_width=5.5,shade = TRUE) popViewport(1) pushViewport(viewport(layout.pos.col = 2)) mosaic(haireye, gp_args = list(interpolate = ipol), margin = c(left=3,right = 1), keep_aspect_ratio = FALSE, newpage = FALSE, shade = TRUE) popViewport(2) ################################################### ### code chunk number 65: bundesliga ################################################### BL <- xtabs(~ HomeGoals + AwayGoals, data = Bundesliga, subset = Year == 1995) mosaic(BL, shade = TRUE) ################################################### ### code chunk number 66: friendly ################################################### mosaic(BL, gp = shading_Friendly, legend = legend_fixed, zero_size = 0) ################################################### ### code chunk number 67: bundesligafig ################################################### pushViewport(viewport(layout = grid.layout(ncol = 2))) pushViewport(viewport(layout.pos.col = 1)) mosaic(BL, margin = c(right = 1), keep_aspect_ratio= FALSE, newpage = FALSE, legend_width=5.5, shade = TRUE) popViewport(1) pushViewport(viewport(layout.pos.col = 2)) mosaic(BL, gp = shading_Friendly, legend = legend_fixed, zero_size = 0, margin = c(right = 1), keep_aspect_ratio= FALSE, newpage = FALSE, legend_width=5.5) popViewport(2) ################################################### ### code chunk number 68: arthritis ################################################### set.seed(4711) mosaic(~ Treatment + Improved, data = Arthritis, subset = Sex == "Female", gp = shading_max) ################################################### ### code chunk number 69: arthritisfig ################################################### set.seed(4711) mosaic(~ Treatment + Improved, data = Arthritis, subset = Sex == "Female", gp = shading_max) ################################################### ### code chunk number 70: default ################################################### mosaic(Titanic) ################################################### ### code chunk number 71: clipping ################################################### mosaic(Titanic, labeling_args = list(clip = c(Survived = TRUE, Age = TRUE))) ################################################### ### code chunk number 72: abbreviating ################################################### mosaic(Titanic, labeling_args = list(abbreviate_labs = c(Survived = TRUE, Age = 3))) ################################################### ### code chunk number 73: rotate ################################################### mosaic(Titanic, labeling_args = list(rot_labels = c(bottom = 90, right = 0), offset_varnames = c(right = 1), offset_labels = c(right = 0.3)), margins = c(right = 4, bottom = 3)) ################################################### ### code chunk number 74: repeat ################################################### mosaic(Titanic, labeling_args = list(rep = c(Survived = FALSE, Age = FALSE))) ################################################### ### code chunk number 75: label1fig ################################################### pushViewport(viewport(layout = grid.layout(ncol = 2,nrow=3))) pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 1)) mosaic(Titanic, newpage = FALSE, keep = TRUE, margin = c(right = 3), gp_labels = gpar(fontsize = 10)) popViewport() pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 1)) mosaic(Titanic, labeling_args = list(clip = c(Survived = TRUE, Age = TRUE)), newpage = FALSE, keep = TRUE, margin = c(left = 3), gp_labels = gpar(fontsize = 10)) popViewport() pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 2)) mosaic(Titanic, labeling_args = list(abbreviate_labs = c(Survived = TRUE, Age = 2)), newpage = FALSE, keep = TRUE, margin = c(right = 3), gp_labels = gpar(fontsize = 10)) popViewport() pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 2)) mosaic(Titanic, labeling_args = list(rep = c(Survived = FALSE, Age = FALSE)), newpage = FALSE, keep = TRUE, margin = c(left = 3), gp_labels = gpar(fontsize = 10)) popViewport() pushViewport(viewport(layout.pos.col = 1:2, layout.pos.row = 3)) pushViewport(viewport(width = 0.55)) mosaic(Titanic, labeling_args = list(rot_labels = c(bottom = 90, right = 0), offset_varnames = c(right = 1), offset_labels = c(right = 0.3)), margins = c(right = 4, bottom = 3), newpage = FALSE, keep = FALSE, gp_labels = gpar(fontsize = 10)) popViewport(3) ################################################### ### code chunk number 76: left ################################################### mosaic(Titanic, labeling_args = list(pos_varnames = "left", pos_labels = "left", just_labels = "left", rep = FALSE)) ################################################### ### code chunk number 77: left2 ################################################### mosaic(Titanic, labeling = labeling_left) ################################################### ### code chunk number 78: margins ################################################### mosaic(Titanic, labeling_args = list(tl_labels = FALSE, tl_varnames = TRUE, abbreviate_labs = c(Survived = 1, Age = 3))) ################################################### ### code chunk number 79: boxes ################################################### mosaic(Titanic, labeling_args = list(tl_labels = FALSE, tl_varnames = TRUE, boxes = TRUE, clip = TRUE)) ################################################### ### code chunk number 80: boxes2 ################################################### mosaic(Titanic, labeling = labeling_cboxed) ################################################### ### code chunk number 81: labbl ################################################### mosaic(Titanic, labeling_args = list(tl_labels = TRUE, boxes = TRUE, clip = c(Survived = FALSE, Age = FALSE, TRUE), abbreviate_labs = c(Age = 4), labbl_varnames = TRUE), margins = c(left = 4, right = 1, 3)) ################################################### ### code chunk number 82: labbl2 ################################################### mosaic(Titanic, labeling = labeling_lboxed, margins = c(right = 4, left = 1, 3)) ################################################### ### code chunk number 83: label2fig ################################################### pushViewport(viewport(layout = grid.layout(ncol = 2, nrow = 2))) pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 1)) mosaic(Titanic, labeling_args = list(pos_varnames = "left", pos_labels = "left", just_labels = "left", rep = FALSE), newpage = FALSE, keep = TRUE, gp_labels = gpar(fontsize = 12)) popViewport() pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 1)) mosaic(Titanic, labeling_args = list(tl_labels = FALSE, tl_varnames = TRUE, abbreviate_labs = c(Survived = 1, Age = 3)), newpage = FALSE, keep = TRUE, margins = c(left = 4, right = 1, 3), gp_labels = gpar(fontsize = 12)) popViewport() pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 2)) mosaic(Titanic, labeling_args = list(tl_labels = FALSE, tl_varnames = TRUE, boxes = TRUE, clip = TRUE), newpage = FALSE, keep = TRUE, gp_labels = gpar(fontsize = 12)) popViewport() pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 2)) mosaic(Titanic, labeling_args = list(tl_labels = TRUE, boxes = TRUE, clip = c(Survived = FALSE, Age = FALSE, TRUE), labbl_varnames = TRUE, abbreviate_labs = c(Age = 4)), margins = c(left = 4, right = 1, 3), newpage = FALSE, keep = TRUE, gp_labels = gpar(fontsize = 12)) popViewport(2) ################################################### ### code chunk number 84: cell ################################################### mosaic(~ MaritalStatus + Gender, data = PreSex, labeling = labeling_cells) ################################################### ### code chunk number 85: cell2 ################################################### mosaic(~ PremaritalSex + ExtramaritalSex, data = PreSex, labeling = labeling_cells(abbreviate_labels = TRUE, abbreviate_varnames = TRUE, clip = FALSE)) ################################################### ### code chunk number 86: conditional ################################################### mosaic(~ PremaritalSex + ExtramaritalSex | MaritalStatus + Gender, data = PreSex, labeling = labeling_conditional(abbreviate_varnames = TRUE, abbreviate_labels = TRUE, clip = FALSE, gp_text = gpar(col = "red"))) ################################################### ### code chunk number 87: text ################################################### mosaic(Titanic, labeling_args = list(abbreviate_labs = c(Survived = 1, Age = 4)), pop = FALSE) tab <- ifelse(Titanic < 6, NA, Titanic) labeling_cells(text = tab, clip = FALSE)(Titanic) ################################################### ### code chunk number 88: label3fig ################################################### grid.newpage() pushViewport(viewport(layout = grid.layout(ncol = 2, nrow = 2))) pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 1)) mosaic(~ MaritalStatus + Gender, data = PreSex, labeling = labeling_cells, newpage = FALSE, keep = TRUE, gp_labels = gpar(fontsize = 10)) popViewport() pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 1)) mosaic(~ PremaritalSex + ExtramaritalSex, data = PreSex, labeling = labeling_cells(abbreviate_labels = TRUE, abbreviate_varnames = TRUE, clip = FALSE), newpage = FALSE, keep = TRUE, gp_labels = gpar(fontsize = 10)) popViewport() pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 2)) mosaic(~ PremaritalSex + ExtramaritalSex | MaritalStatus + Gender, data = PreSex, labeling = labeling_conditional(abbreviate_varnames = TRUE, abbreviate_labels = TRUE, clip = FALSE, gp_text = gpar(col = "red")), newpage = FALSE, keep = TRUE, gp_labels = gpar(fontsize = 10)) popViewport() pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 2)) mosaic(Titanic, labeling_args = list(abbreviate_labs = c(Survived = 1, Age = 3)), pop = FALSE, newpage = FALSE, keep = TRUE, gp_labels = gpar(fontsize = 10)) tab <- ifelse(Titanic < 6, NA, Titanic) labeling_cells(text = tab, clip = FALSE)(Titanic) ################################################### ### code chunk number 89: list ################################################### mosaic(Titanic, labeling = labeling_list, margins = c(bottom = 5)) ################################################### ### code chunk number 90: listfig ################################################### mosaic(Titanic, labeling = labeling_list, margins = c(bottom = 5), keep = TRUE) ################################################### ### code chunk number 91: artspine ################################################### (art <- structable(~Treatment + Improved, data = Arthritis, split_vertical = TRUE)) (my_spacing <- list(unit(0.5, "lines"), unit(c(0, 0), "lines"))) my_colors <- c("lightgray", "lightgray", "black") mosaic(art, spacing = my_spacing, gp = gpar(fill = my_colors, col = my_colors)) ################################################### ### code chunk number 92: artspinefig ################################################### (art <- structable(~Treatment + Improved, data = Arthritis, split_vertical = TRUE)) (my_spacing <- list(unit(0.5, "lines"), unit(c(0, 0), "lines"))) my_colors <- c("lightgray", "lightgray", "black") mosaic(art, spacing = my_spacing, gp = gpar(fill = my_colors, col = my_colors)) ################################################### ### code chunk number 93: artspine ################################################### mosaic(Improved ~ Treatment, data = Arthritis, split_vertical = TRUE) ################################################### ### code chunk number 94: space1 ################################################### mosaic(art, spacing = spacing_equal(unit(2, "lines"))) ################################################### ### code chunk number 95: space2 ################################################### mosaic(art, spacing = spacing_dimequal(unit(1:2, "lines"))) ################################################### ### code chunk number 96: space3 ################################################### mosaic(art, spacing = spacing_increase(start = unit(0.5, "lines"), rate = 1.5)) ################################################### ### code chunk number 97: spine4 ################################################### mosaic(art, spacing = spacing_highlighting, gp = my_colors) ################################################### ### code chunk number 98: spacingfig ################################################### pushViewport(viewport(layout = grid.layout(ncol = 2, nrow = 2))) pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 1)) mosaic(art, spacing = spacing_equal(unit(2, "lines")), keep = TRUE, newpage = FALSE) popViewport() pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 1)) mosaic(art, spacing = spacing_dimequal(unit(c(0.5, 2), "lines")), keep = TRUE, newpage = FALSE) popViewport() pushViewport(viewport(layout.pos.col = 1, layout.pos.row = 2)) mosaic(art, spacing = spacing_increase(start = unit(0.3, "lines"), rate = 2.5), keep = TRUE, newpage = FALSE) popViewport() pushViewport(viewport(layout.pos.col = 2, layout.pos.row = 2)) mosaic(art, spacing = spacing_highlighting, keep = TRUE, newpage = FALSE) popViewport(2) ################################################### ### code chunk number 99: oc1 ################################################### tab <- xtabs(Freq ~ stage + operation + xray + survival, data = OvaryCancer) ################################################### ### code chunk number 100: oc2 ################################################### structable(survival ~ ., data = tab) ################################################### ### code chunk number 101: oc3 ################################################### dpa <- list(var_offset = 1.2, rot = -30, just_leveltext= "left") pairs(tab, diag_panel = pairs_barplot, diag_panel_args = dpa) ################################################### ### code chunk number 102: ocpairs ################################################### dpa <- list(var_offset = 1.2, rot = -30, just_leveltext= "left") pairs(tab, diag_panel = pairs_barplot, diag_panel_args = dpa) ################################################### ### code chunk number 103: oc4 ################################################### doubledecker(survival ~ stage + operation + xray, data = tab) ################################################### ### code chunk number 104: ocdoubledecker ################################################### doubledecker(survival ~ stage + operation + xray, data = tab) ################################################### ### code chunk number 105: oc6 ################################################### split <- c(TRUE, TRUE, TRUE, FALSE) mosaic(tab, expected = ~ survival + operation * xray * stage, split_vertical = split) ################################################### ### code chunk number 106: ocmosaicnull ################################################### split <- c(TRUE, TRUE, TRUE, FALSE) mosaic(tab, expected = ~ survival + operation * xray * stage, split_vertical = split) ################################################### ### code chunk number 107: oc7 ################################################### mosaic(tab, expected = ~ (survival + operation * xray) * stage, split_vertical = split) ################################################### ### code chunk number 108: ocmosaicstage ################################################### mosaic(tab, expected = ~ (survival + operation * xray) * stage, split_vertical = split)
/scratch/gouwar.j/cran-all/cranData/vcd/inst/doc/strucplot.R
# Cochran-Mantel-Haenszel tests for ordinal factors in contingency tables # The code below follows Stokes, Davis & Koch, (2000). # "Categorical Data Analysis using the SAS System", 2nd Ed., # pp 74--75, 92--101, 124--129. # Ref: Landis, R. J., Heyman, E. R., and Koch, G. G. (1978), # Average Partial Association in Three-way Contingency Tables: # A Review and Discussion of Alternative Tests, # International Statistical Review, 46, 237-254. # See: https://onlinecourses.science.psu.edu/stat504/book/export/html/90 # http://support.sas.com/documentation/cdl/en/statug/63033/HTML/default/viewer.htm#statug_freq_a0000000648.htm # DONE: this should be the main function, handling 2-way & higher-way tables # With strata, use apply() or recursion over strata # DONE: With strata, calculate overall CMH tests controlling for strata # FIXED: rmeans and cmeans tests were labeled incorrectly CMHtest <- function(x, ...) UseMethod("CMHtest") CMHtest.formula <- function(formula, data = NULL, subset = NULL, na.action = NULL, ...) { m <- match.call(expand.dots = FALSE) edata <- eval(m$data, parent.frame()) fstr <- strsplit(paste(deparse(formula), collapse = ""), "~") vars <- strsplit(strsplit(gsub(" ", "", fstr[[1]][2]), "\\|")[[1]], "\\+") varnames <- vars[[1]] condnames <- if (length(vars) > 1) vars[[2]] else NULL dep <- gsub(" ", "", fstr[[1]][1]) if (!dep %in% c("","Freq")) { if (all(varnames == ".")) { varnames <- if (is.data.frame(data)) colnames(data) else names(dimnames(as.table(data))) varnames <- varnames[-which(varnames %in% dep)] } varnames <- c(varnames, dep) } if (inherits(edata, "ftable") || inherits(edata, "table") || length(dim(edata)) > 2) { condind <- NULL dat <- as.table(data) if(all(varnames != ".")) { ind <- match(varnames, names(dimnames(dat))) if (any(is.na(ind))) stop(paste("Can't find", paste(varnames[is.na(ind)], collapse=" / "), "in", deparse(substitute(data)))) if (!is.null(condnames)) { condind <- match(condnames, names(dimnames(dat))) if (any(is.na(condind))) stop(paste("Can't find", paste(condnames[is.na(condind)], collapse=" / "), "in", deparse(substitute(data)))) ind <- c(condind, ind) } dat <- margin.table(dat, ind) } CMHtest.default(dat, strata = if (is.null(condind)) NULL else match(condnames, names(dimnames(dat))), ...) } else { m <- m[c(1, match(c("formula", "data", "subset", "na.action"), names(m), 0))] m[[1]] <- as.name("xtabs") m$formula <- formula(paste(if("Freq" %in% colnames(data)) "Freq", "~", paste(c(varnames, condnames), collapse = "+"))) tab <- eval(m, parent.frame()) CMHtest.default(tab, ...) } } CMHtest.default <- function(x, strata = NULL, rscores=1:R, cscores=1:C, types=c("cor", "rmeans", "cmeans", "general"), overall=FALSE, details=overall, ...) { snames <- function(x, strata) { sn <- dimnames(x)[strata] dn <- names(sn) apply(expand.grid(sn), 1, function(x) paste(dn, x, sep=":", collapse = "|")) } ## check dimensions L <- length(d <- dim(x)) if(any(d < 2L)) stop("All table dimensions must be 2 or greater") if(L > 2L & is.null(strata)) strata <- 3L:L if(is.character(strata)) strata <- which(names(dimnames(x)) == strata) if(L - length(strata) != 2L) stop("All but 2 dimensions must be specified as strata.") ## rearrange table to put primary dimensions first x <- aperm(x, c(setdiff(1:L, strata), strata)) d <- dim(x) R <- d[1] C <- d[2] # handle strata if (!is.null(strata)) { sn <- snames(x, strata) res <- c(apply(x, strata, CMHtest2, rscores=rscores, cscores=cscores, types=types,details=details, ...)) # DONE: fix names if there are 2+ strata names(res) <- sn for (i in seq_along(res)) res[[i]]$stratum <- sn[i] # DONE: Calculate generalized CMH, controlling for strata if (overall) { if (!details) warning("Overall CMH tests not calculated because details=FALSE") else { resall <- CMHtest3(res, types=types) res$ALL <- resall } } return(res) } else CMHtest2(x, rscores=rscores, cscores=cscores, types=types,details=details, ...) } # handle two-way case, for a given stratum # DONE: now allow rscores/cscores == 'midrank' for midrank scores # DONE: allow rscores/cscores=NULL for unordered factors, where ordinal # scores don't make sense # DONE: modified to return all A matrices as a list # DONE: cmh() moved outside CMHtest2 <- function(x, stratum=NULL, rscores=1:R, cscores=1:C, types=c("cor", "rmeans", "cmeans", "general"), details=FALSE, ...) { # left kronecker product lkronecker <- function(x, y, make.dimnames=TRUE, ...) kronecker(y, x, make.dimnames=make.dimnames, ...) # midrank scores (modified ridits) based on row/column totals midrank <- function (n) { cs <- cumsum(n) (2*cs - n +1) / (2*(cs[length(cs)]+1)) } L <- length(d <- dim(x)) R <- d[1] C <- d[2] if (is.character(rscores) && rscores=="midrank") rscores <- midrank(rowSums(x)) if (is.character(cscores) && cscores=="midrank") cscores <- midrank(colSums(x)) nt <- sum(x) pr <- rowSums(x) / nt pc <- colSums(x) / nt m <- as.vector(nt * outer(pr,pc)) # expected values under independence n <- as.vector(x) # cell frequencies V1 <- (diag(pr) - pr %*% t(pr)) V2 <- (diag(pc) - pc %*% t(pc)) V <- (nt^2/(nt-1)) * lkronecker(V1, V2, make.dimnames=TRUE) if (length(types)==1 && types=="ALL") types <- c("general", "rmeans", "cmeans", "cor" ) types <- match.arg(types, several.ok=TRUE) # handle is.null(rscores) etc here if (is.null(rscores)) types <- setdiff(types, c("cmeans", "cor")) if (is.null(cscores)) types <- setdiff(types, c("rmeans", "cor")) table <- NULL Amats <- list() for (type in types) { if("cor" == type) { A <- lkronecker( t(rscores), t(cscores) ) df <- 1 table <- rbind(table, cmh(n, m, A, V, df)) Amats$cor <- A } else if("rmeans" == type) { A <- lkronecker( cbind(diag(R-1), rep(0, R-1)), t(cscores)) df <- R-1 table <- rbind(table, cmh(n, m, A, V, df)) Amats$rmeans <- A } else if("cmeans" == type) { A <- lkronecker( t(rscores), cbind(diag(C-1), rep(0, C-1))) df <- C-1 table <- rbind(table, cmh(n, m, A, V, df)) Amats$cmeans <- A } else if ("general" == type) { A <- lkronecker( cbind(diag(R-1), rep(0, R-1)), cbind(diag(C-1), rep(0, C-1))) df <- (R-1)*(C-1) table <- rbind(table, cmh(n, m, A, V, df)) Amats$general <- A } } colnames(table) <- c("Chisq", "Df", "Prob") rownames(table) <- types xnames <- names(dimnames(x)) result <- list(table=table, names=xnames, rscores=rscores, cscores=cscores, stratum=stratum ) if (details) result <- c(result, list(A=Amats, V=V, n=n, m=m)) class(result) <- "CMHtest" result } # do overall test, from a computed CMHtest list CMHtest3 <- function(object, types=c("cor", "rmeans", "cmeans", "general")) { nstrat <- length(object) # number of strata # extract components, each a list of nstrat terms n.list <- lapply(object, function(s) s$n) m.list <- lapply(object, function(s) s$m) V.list <- lapply(object, function(s) s$V) A.list <- lapply(object, function(s) s$A) nt <- sapply(lapply(object, function(s) s$n), sum) Df <- object[[1]]$table[,"Df"] if (length(types)==1 && types=="ALL") types <- c("general", "rmeans", "cmeans", "cor" ) types <- match.arg(types, several.ok=TRUE) table <- list() for (type in types) { AVA <- 0 Anm <- 0 for (k in 1:nstrat) { A <- A.list[[k]][[type]] V <- V.list[[k]] n <- n.list[[k]] m <- m.list[[k]] AVA <- AVA + A %*% V %*% t(A) Anm <- Anm + A %*% (n-m) } Q <- t(Anm) %*% solve(AVA) %*% Anm df <- Df[type] pvalue <- pchisq(Q, df, lower.tail=FALSE) table <- rbind(table, c(Q, df, pvalue)) } rownames(table) <- types colnames(table) <- c("Chisq", "Df", "Prob") xnames <- object[[1]]$names result=list(table=table, names=xnames, stratum="ALL") class(result) <- "CMHtest" result } # basic CMH calculation cmh <- function(n, m,A, V, df) { AVA <- A %*% V %*% t(A) Q <- t(n-m) %*% t(A) %*% solve(AVA) %*% A %*% (n-m) pvalue <- pchisq(Q, df, lower.tail=FALSE) c(Q, df, pvalue) } # DONE: incorporate stratum name in the heading # TODO: handle the printing of pvalues better print.CMHtest <- function(x, digits = max(getOption("digits") - 2, 3), ...) { heading <- "Cochran-Mantel-Haenszel Statistics" if (!is.null(x$names)) heading <- paste(heading, "for", paste(x$names, collapse=" by ")) if (!is.null(x$stratum)) heading <- paste(heading, ifelse(x$stratum=="ALL", "\n\tOverall tests, controlling for all strata", paste("\n\tin stratum", x$stratum))) # TODO: determine score types (integer, midrank) for heading df <- x$table types <- rownames(df) labels <- list(cor="Nonzero correlation", rmeans="Row mean scores differ", cmeans="Col mean scores differ", general="General association") labels <- unlist(labels[types]) # select the labels for the types df <- data.frame("AltHypothesis"=as.character(labels), df, stringsAsFactors=FALSE) cat(heading,"\n\n") print(df, digits=digits, ...) cat("\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/CMHtest.R
# crossings model (Goodman, 1972) # Ref: #Goodman, L. (1972). Some multiplicative models for the analysis of cross-classified data. #In: Proceedings of the Sixth Berkeley Symposium on Mathematical Statistics and Probability, #Berkeley, CA: University of California Press, pp. 649-696. crossings <- function(i, j, n) { npar <- n - 1 result <- list() for(c in 1:npar) { overi <- c >= i overj <- c >= j result[[c]] <- (overi & !overj) + (overj & !overi) } result <- matrix(unlist(result), length(i), npar) colnames(result) <- paste('C', 1:npar, sep='') result } Crossings <- function(...) { dots <- list(...) if (length(dots) != 2) stop("Crossings() is defined for only two factors") if (length(dots[[1]]) != length(dots[[2]])) stop("arguments to Crossings() must all have same length") dots <- lapply(dots, as.factor) n <- nlevels(dots[[1]]) if (nlevels(dots[[2]]) != n) stop("arguments to Crossings() must all have same number of levels") result <- crossings(as.numeric(dots[[1]]), as.numeric(dots[[2]]), n) rownames(result) <- do.call("paste", c(dots, sep = "")) result }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/Crossings.R
# Calculate Goodman-Kruskal Gamma # Original from: Laura Thompson, # https://home.comcast.net/~lthompson221/Splusdiscrete2.pdf GKgamma<-function(x, level=0.95) { # x is a matrix of counts. You can use output of crosstabs or xtabs in R. # Confidence interval calculation and output from Greg Rodd # Check for using S-PLUS and output is from crosstabs (needs >= S-PLUS 6.0) if(is.null(version$language) && inherits(x, "crosstabs")) { oldClass(x)<-NULL; attr(x, "marginals")<-NULL} ## TODO: add tests for matrix or table n <- nrow(x) m <- ncol(x) pi.c<-pi.d<-matrix(0, nrow=n, ncol=m) row.x<-row(x) col.x<-col(x) for(i in 1:(n)){ for(j in 1:(m)){ pi.c[i, j]<-sum(x[row.x<i & col.x<j]) + sum(x[row.x>i & col.x>j]) pi.d[i, j]<-sum(x[row.x<i & col.x>j]) + sum(x[row.x>i & col.x<j]) } } C <- sum(pi.c*x)/2 D <- sum(pi.d*x)/2 psi<-2*(D*pi.c-C*pi.d)/(C+D)^2 sigma2<-sum(x*psi^2)-sum(x*psi)^2 gamma <- (C - D)/(C + D) pr2 <- 1 - (1 - level)/2 CI <- qnorm(pr2) * sqrt(sigma2) * c(-1, 1) + gamma result <- list(gamma = gamma, C = C, D = D, sigma = sqrt(sigma2), CIlevel = level, CI = c(max(CI[1], -1), min(CI[2], 1)) ) class(result) <- "GKgamma" result } print.GKgamma <- function (x, digits = 3, ...) { cat("gamma :", round(x$gamma, digits = digits), "\n") cat("std. error :", round(x$sigma, digits = digits), "\n") cat("CI :", round(x$CI, digits = digits), "\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/GKgamma.R
# Functions for Hosmer Lemeshow test # original function downloaded from # http://sas-and-r.blogspot.com/2010/09/example-87-hosmer-and-lemeshow-goodness.html # # see also: MKmisc::gof.test for more general versions HLtest <- HosmerLemeshow <- function(model, g=10) { if (!inherits(model, "glm")) stop("requires a binomial family glm") if (!family(model)$family == 'binomial') stop("requires a binomial family glm") y <- model$y yhat <- model$fitted.values cutyhat = cut(yhat, breaks = quantile(yhat, probs=seq(0, 1, 1/g)), include.lowest=TRUE) obs = xtabs(cbind(1 - y, y) ~ cutyhat) exp = xtabs(cbind(1 - yhat, yhat) ~ cutyhat) chi = (obs - exp)/sqrt(exp) # browser() table <- data.frame(cut=dimnames(obs)$cutyhat, total= as.numeric(apply(obs, 1, sum)), obs=as.numeric(as.character(obs[,1])), exp=as.numeric(as.character(exp[,1])), chi=as.numeric(as.character(chi[,1])) ) rownames(table) <- 1:g chisq = sum(chi^2) p = 1 - pchisq(chisq, g - 2) result <- list(table=table, chisq=chisq, df=g-2, p.value=p, groups=g, call=model$call) class(result) <- "HLtest" return(result) } print.HLtest <- function(x, ...) { heading <- "Hosmer and Lemeshow Goodness-of-Fit Test" df <- data.frame("ChiSquare"=x$chisq, df=x$df, "P_value"= x$p.value) cat(heading,"\n\n") cat("Call:\n") print(x$call) print(df, row.names=FALSE) invisible(x) } # Q: how to print **s next to larg chisq components? summary.HLtest <- function(object, ...) { heading <- "Partition for Hosmer and Lemeshow Goodness-of-Fit Test" cat(heading,"\n\n") print(object$table) print(object) } ## Q: how to display any large chi residuals on the bars?? rootogram.HLtest <- function(x, ...) { rootogram(as.numeric(x$table$obs), as.numeric(x$table$exp), xlab="Fitted value group", names=1:x$groups, ...) } plot.HLtest <- function(x, ...) { rootogram.HLtest(x, ...) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/HLtest.R
# Generate and fit all 1-way, 2-way, ... k-way terms in a glm Kway <- function(formula, family=poisson, data, ..., order=nt, prefix="kway") { if (is.character(family)) family <- get(family, mode = "function", envir = parent.frame()) if (is.function(family)) family <- family() if (is.null(family$family)) { print(family) stop("'family' not recognized") } if (missing(data)) data <- environment(formula) models <- list() mod <- glm(formula, family=family, data, ...) mod$call$formula <- formula terms <- terms(formula) tl <- attr(terms, "term.labels") nt <- length(tl) models[[1]] <- mod for(i in 2:order) { models[[i]] <- update(mod, substitute(.~.^p, list(p = i))) } # null model mod0 <- update(mod, .~1) models <- c(list(mod0), models) names(models) <- paste(prefix, 0:order, sep = ".") class(models) <- "glmlist" models }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/Kway.R
# fixed buglet when deviance() returns a null # fixed bug: residual df calculated incorrectly # but this now depends on objects having a df.residual component # TRUE for lm, glm, polr, negbin objects # made generic, adding a glmlist method LRstats <- function(object, ...) { UseMethod("LRstats") } LRstats.glmlist <- function(object, ..., saturated = NULL, sortby=NULL) { ns <- sapply(object, function(x) length(x$residuals)) if (any(ns != ns[1L])) stop("models were not all fitted to the same size of dataset") nmodels <- length(object) if (nmodels == 1) return(LRstats.default(object[[1L]], saturated=saturated)) rval <- lapply(object, LRstats.default, saturated=saturated) rval <- do.call(rbind, rval) if (!is.null(sortby)) { rval <- rval[order(rval[,sortby], decreasing=TRUE),] } rval } # could just do LRstats.loglmlist <- LRstats.glmlist LRstats.loglmlist <- function(object, ..., saturated = NULL, sortby=NULL) { ns <- sapply(object, function(x) length(x$residuals)) if (any(ns != ns[1L])) stop("models were not all fitted to the same size of dataset") nmodels <- length(object) if (nmodels == 1) return(LRstats.default(object[[1L]], saturated=saturated)) rval <- lapply(object, LRstats.default, saturated=saturated) rval <- do.call(rbind, rval) if (!is.null(sortby)) { rval <- rval[order(rval[,sortby], decreasing=TRUE),] } rval } LRstats.default <- function(object, ..., saturated = NULL, sortby=NULL) { ## interface methods for logLik() and nobs() ## - use S4 methods if loaded ## - use residuals() if nobs() is not available logLik0 <- if("stats4" %in% loadedNamespaces()) stats4::logLik else logLik nobs0 <- function(x, ...) { nobs1 <- if("stats4" %in% loadedNamespaces()) stats4::nobs else nobs nobs2 <- function(x, ...) NROW(residuals(x, ...)) rval <- try(nobs1(x, ...), silent = TRUE) if(inherits(rval, "try-error") | is.null(rval)) rval <- nobs2(x, ...) return(rval) } dof <- function(x) { if (inherits(x, "loglm")) { rval <- x$df } else { rval <- try(x$df.residual, silent=TRUE) } if (inherits(rval, "try-error") || is.null(rval)) stop(paste("Can't determine residual df for a", class(x), "object")) rval } ## collect all objects objects <- list(object, ...) nmodels <- length(objects) ## check sample sizes ns <- sapply(objects, nobs0) if(any(ns != ns[1L])) stop("models were not all fitted to the same size of dataset") ## extract log-likelihood and df (number of parameters) ll <- lapply(objects, logLik0) par <- as.numeric(sapply(ll, function(x) attr(x, "df"))) df <- as.numeric(sapply(objects, function(x) dof(x))) ll <- sapply(ll, as.numeric) ## compute saturated reference value (use 0 if deviance is not available) if(is.null(saturated)) { dev <- try(sapply(objects, deviance), silent = TRUE) if(inherits(dev, "try-error") || any(sapply(dev, is.null))) { saturated <- 0 } else { saturated <- ll + dev/2 } } ## setup ANOVA-style matrix rval <- matrix(rep(NA, 5 * nmodels), ncol = 5) colnames(rval) <- c("AIC", "BIC", "LR Chisq", "Df", "Pr(>Chisq)") rownames(rval) <- as.character(sapply(match.call(), deparse)[-1L])[1:nmodels] rval[,1] <- -2 * ll + 2 * par rval[,2] <- -2 * ll + log(ns) * par rval[,3] <- -2 * (ll - saturated) rval[,4] <- df rval[,5] <- pchisq(rval[,3], df, lower.tail = FALSE) if (!is.null(sortby)) { rval <- rval[order(rval[,sortby], decreasing=TRUE),] } ## return structure(as.data.frame(rval), heading = "Likelihood summary table:", class = c("anova", "data.frame")) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/LRstats.R
# fixed buglet when deviance() returns a null # fixed bug: residual df calculated incorrectly # but this now depends on objects having a df.residual component # TRUE for lm, glm, polr, negbin objects # made generic, adding a glmlist method Summarise <- function(object, ...) { UseMethod("Summarise") } Summarise.glmlist <- function(object, ..., saturated = NULL, sortby=NULL) { ns <- sapply(object, function(x) length(x$residuals)) if (any(ns != ns[1L])) stop("models were not all fitted to the same size of dataset") nmodels <- length(object) if (nmodels == 1) return(Summarise.default(object[[1L]], saturated=saturated)) rval <- lapply(object, Summarise.default, saturated=saturated) rval <- do.call(rbind, rval) if (!is.null(sortby)) { rval <- rval[order(rval[,sortby], decreasing=TRUE),] } rval } # could just do Summarise.loglmlist <- Summarise.glmlist Summarise.loglmlist <- function(object, ..., saturated = NULL, sortby=NULL) { ns <- sapply(object, function(x) length(x$residuals)) if (any(ns != ns[1L])) stop("models were not all fitted to the same size of dataset") nmodels <- length(object) if (nmodels == 1) return(Summarise.default(object[[1L]], saturated=saturated)) rval <- lapply(object, Summarise.default, saturated=saturated) rval <- do.call(rbind, rval) if (!is.null(sortby)) { rval <- rval[order(rval[,sortby], decreasing=TRUE),] } rval } Summarise.default <- function(object, ..., saturated = NULL, sortby=NULL) { ## interface methods for logLik() and nobs() ## - use S4 methods if loaded ## - use residuals() if nobs() is not available logLik0 <- if("stats4" %in% loadedNamespaces()) stats4::logLik else logLik nobs0 <- function(x, ...) { nobs1 <- if("stats4" %in% loadedNamespaces()) stats4::nobs else nobs nobs2 <- function(x, ...) NROW(residuals(x, ...)) rval <- try(nobs1(x, ...), silent = TRUE) if(inherits(rval, "try-error") | is.null(rval)) rval <- nobs2(x, ...) return(rval) } dof <- function(x) { if (inherits(x, "loglm")) { rval <- x$df } else { rval <- try(x$df.residual, silent=TRUE) } if (inherits(rval, "try-error") || is.null(rval)) stop(paste("Can't determine residual df for a", class(x), "object")) rval } ## collect all objects objects <- list(object, ...) nmodels <- length(objects) ## check sample sizes ns <- sapply(objects, nobs0) if(any(ns != ns[1L])) stop("models were not all fitted to the same size of dataset") ## extract log-likelihood and df (number of parameters) ll <- lapply(objects, logLik0) par <- as.numeric(sapply(ll, function(x) attr(x, "df"))) df <- as.numeric(sapply(objects, function(x) dof(x))) ll <- sapply(ll, as.numeric) ## compute saturated reference value (use 0 if deviance is not available) if(is.null(saturated)) { dev <- try(sapply(objects, deviance), silent = TRUE) if(inherits(dev, "try-error") || any(sapply(dev, is.null))) { saturated <- 0 } else { saturated <- ll + dev/2 } } ## setup ANOVA-style matrix rval <- matrix(rep(NA, 5 * nmodels), ncol = 5) colnames(rval) <- c("AIC", "BIC", "LR Chisq", "Df", "Pr(>Chisq)") rownames(rval) <- as.character(sapply(match.call(), deparse)[-1L])[1:nmodels] rval[,1] <- -2 * ll + 2 * par rval[,2] <- -2 * ll + log(ns) * par rval[,3] <- -2 * (ll - saturated) rval[,4] <- df rval[,5] <- pchisq(rval[,3], df, lower.tail = FALSE) if (!is.null(sortby)) { rval <- rval[order(rval[,sortby], decreasing=TRUE),] } ## return structure(as.data.frame(rval), heading = "Likelihood summary table:", class = c("anova", "data.frame")) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/Summarise.R
# calculate bivariate logits and OR blogits <- function(Y, add, colnames, row.vars, rev=FALSE) { if (ncol(Y) != 4) stop("Y must have 4 columns") if (missing(add)) add <- if (any(Y==0)) 0.5 else 0 Y <- Y + add if (rev) Y <- Y[,4:1] L <- matrix(0, nrow(Y), 3) L[,1] <- log( (Y[,1] + Y[,2]) / (Y[,3] + Y[,4]) ) L[,2] <- log( (Y[,1] + Y[,3]) / (Y[,2] + Y[,4]) ) L[,3] <- log( (Y[,1] * Y[,4]) / ((Y[,2] * Y[,3])) ) cn <- c("logit1", "logit2", "logOR") colnames(L) <- if(missing(colnames)) cn else c(colnames, cn[-(1:length(colnames))]) if(!missing(row.vars)) L <- cbind(L, row.vars) L }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/blogits.R
# collapse a contingency table or ftable by re-assigning levels of table variables # revised to accept an array also collapse.table <- function(table, ...) { nargs <- length(args <- list(...)) if (!nargs) return(table) if (inherits(table, "ftable")) table <- as.table(table) if (inherits(table, "array")) table <- as.table(table) if (inherits(table, "table")) { tvars <- names(dimnames(table)) table <- as.data.frame.table(table) freq <- table[,"Freq"] } else stop("Argument must be a table, array or ftable object") names <- names(args) for (i in 1:nargs) { vals <- args[[i]] nm <- names[[i]] if(any(nm==tvars)) levels(table[[nm]]) <- vals else warning(nm, " is not among the table variables.") } # term <- paste(tvars, collapse = '+') # form <- as.formula(paste("freq ~", term)) # cat("term: ", term, "\n") xtabs(as.formula(paste("freq ~", paste(tvars, collapse = '+'))), data=table) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/collapse.table.R
# Cut a variable to a factor cutfac <- function(x, breaks = NULL, q=10) { if(is.null(breaks)) breaks <- unique(quantile(x, 0:q/q)) x <- cut(x, breaks, include.lowest = TRUE, right = FALSE) levels(x) <- paste(breaks[-length(breaks)], ifelse(diff(breaks) > 1, c(paste("-", breaks[-c(1, length(breaks))] - 1, sep = ""), "+"), ""), sep = "") return(x) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/cutfac.R
### return a data.frame giving brief summaries of data sets in packages # package: a character vector giving the package(s) to look in # allClass: include all classes of the item (TRUE) or just the last class (FALSE) # incPackage: include package name in result? # maxTitle: maximum length of data set Title datasets <- function(package, allClass=FALSE, incPackage=length(package) > 1, maxTitle=NULL) { # make sure requested packages are available and loaded for (i in seq_along(package)) { if (!isNamespaceLoaded(package[i])) if (requireNamespace(package[i], quietly=TRUE)) cat(paste("Loading package:", package[i], "\n")) else stop(paste("Package", package[i], "is not available")) } dsitems <- data(package=package)$results wanted <- c('Package', 'Item','Title') ds <- as.data.frame(dsitems[,wanted], stringsAsFactors=FALSE) getData <- function(x, pkg) { # fix items with " (...)" in names, e.g., "BJsales.lead (BJsales)" in datasets objname <- gsub(" .*", "", x) e <- loadNamespace(pkg) if (!exists(x, envir = e)) { dataname <- sub("^.*\\(", "", x) dataname <- sub("\\)$", "", dataname) e <- new.env() data(list = dataname, package = pkg, envir = e) } get(objname, envir = e) } getDim <- function(i) { data <- getData(ds$Item[i], ds$Package[i]) if (is.null(dim(data))) length(data) else paste(dim(data), collapse='x') } getClass <- function(i) { data <- getData(ds$Item[i], ds$Package[i]) cl <- class(data) if (length(cl)>1 && !allClass) cl[length(cl)] else cl } ds$dim <- unlist(lapply(seq_len(nrow(ds)), getDim )) ds$class <- unlist(lapply(seq_len(nrow(ds)), getClass )) if (!is.null(maxTitle)) ds$Title <- substr(ds$Title, 1, maxTitle) if (incPackage) ds[c('Package', 'Item','class','dim','Title')] else ds[c('Item','class','dim','Title')] }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/datasets.R
# Originally from Marc Schwarz # Ref: http://tolstoy.newcastle.edu.au/R/e6/help/09/01/1873.html # 23 Feb 22: Fix warning from type.convert expand.dft <- function(x, var.names = NULL, freq = "Freq", ...) { # allow: a table object, or a data frame in frequency form if(inherits(x, "table")) x <- as.data.frame.table(x, responseName = freq) freq.col <- which(colnames(x) == freq) if (length(freq.col) == 0) stop(paste(sQuote("freq"), "not found in column names")) DF <- sapply(1:nrow(x), function(i) x[rep(i, each = x[i, freq.col, drop = TRUE]), ], simplify = FALSE) DF <- do.call("rbind", DF)[, -freq.col, drop=FALSE] for (i in 1:ncol(DF)) { DF[[i]] <- type.convert(as.character(DF[[i]]), as.is=TRUE, ...) ## DONE ##: Generates warning: ## 1: In type.convert.default(as.character(DF[[i]]), ...) : ## 'as.is' should be specified by the caller; using TRUE } rownames(DF) <- NULL if (!is.null(var.names)) { if (length(var.names) < dim(DF)[2]) { stop(paste("Too few", sQuote("var.names"), "given.")) } else if (length(var.names) > dim(DF)[2]) { stop(paste("Too many", sQuote("var.names"), "given.")) } else { names(DF) <- var.names } } DF } # make this a synonym expand.table <- expand.dft
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/expand.dft.R
# glmlist - make a glmlist object containing a list of fitted glm objects with their names # borrowing code from Hmisc::llist glmlist <- function(...) { args <- list(...); lname <- names(args) name <- vname <- as.character(sys.call())[-1] for (i in 1:length(args)) { vname[i] <- if (length(lname) && lname[i] != "") lname[i] else name[i] } names(args) <- vname[1:length(args)] is.glm <- unlist(lapply(args, function(x) inherits(x, "glm"))) if (!all(is.glm)) { warning("Objects ", paste(vname[!is.glm], collapse=', '), " removed because they are not glm objects") args <- args[is.glm] } class(args) <- "glmlist" return(args); } # loglmlist - do the same for loglm objects loglmlist <- function(...) { args <- list(...); lname <- names(args) name <- vname <- as.character(sys.call())[-1] for (i in 1:length(args)) { vname[i] <- if (length(lname) && lname[i] != "") lname[i] else name[i] } names(args) <- vname[1:length(args)] is.loglm <- unlist(lapply(args, function(x) inherits(x, "loglm"))) if (!all(is.loglm)) { warning("Objects ", paste(vname[!is.loglm], collapse=', '), " removed because they are not loglm objects") args <- args[is.loglm] } class(args) <- "loglmlist" return(args); } # generic version: named list nlist <- function(...) { args <- list(...); lname <- names(args) name <- vname <- as.character(sys.call())[-1] for (i in 1:length(args)) { vname[i] <- if (length(lname) && lname[i] != "") lname[i] else name[i] } names(args) <- vname[1:length(args)] return(args); } # coeficient method for a glmlist (from John Fox, r-help, 10-28-2014) coef.glmlist <- function(object, result=c("list", "matrix", "data.frame"), ...){ result <- match.arg(result) coefs <- lapply(object, coef) if (result == "list") return(coefs) coef.names <- unique(unlist(lapply(coefs, names))) n.mods <- length(object) coef.matrix <- matrix(NA, length(coef.names), n.mods) rownames(coef.matrix) <- coef.names colnames(coef.matrix) <- names(object) for (i in 1:n.mods){ coef <- coef(object[[i]]) coef.matrix[names(coef), i] <- coef } if (result == "matrix") return(coef.matrix) as.data.frame(coef.matrix) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/glmlist.R
# logLik method for loglm objects, to allow use of AIC() and BIC() # with MASS::loglm, giving comparable results to the use of these # functions with glm(..., family=poisson) models. # allow for non-integer frequencies # allow for zero frequencies, with a zero= argument logLik.loglm <- function(object, ..., zero=1E-10) { fr <- if(!is.null(object$frequencies)) unclass(object$frequencies) else { unclass(update(object, keep.frequencies = TRUE)$frequencies) } df <- prod(dim(fr)) - object$df if (any(fr==0)) { fr <- as.vector(fr) fr[fr==0] <- zero } structure(sum((log(fr) - 1) * fr - lgamma(fr + 1)) - object$deviance/2, df = df, class = "logLik") }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/logLik.loglm.R
#' Loglinear Model Utilities #' These functions generate lists of terms to specify a loglinear model #' in a form compatible with loglin and provide for conversion to an #' equivalent loglm specification. They allow for a more conceptual #' way to specify such models. #' models of joint independence, of some factors wrt one or more other factors #' @param nf number of factors for which to generate model #' @param table a contingency table used for factor names, typically the output from \code{\link[base]{table}} #' @param factors names of factors used in the model when \code{table} is not specified #' @param with indices of the factors against which others are considered jointly independent #' @rdname loglin-utilities #' @export joint <- function(nf, table=NULL, factors=1:nf, with=nf) { if (!is.null(table)) factors <- names(dimnames(table)) if (nf == 1) return (list(term1=factors[1])) if (nf == 2) return (list(term1=factors[1], term2=factors[2])) others <- setdiff(1:nf, with) result <- list(term1=factors[others], term2=factors[with]) result } #' models of conditional independence of some factors wrt one or more other factors #' @param nf number of factors for which to generate model #' @param table a contingency table used for factor names, typically the output from \code{\link[base]{table}} #' @param factors names of factors used in the model when \code{table} is not specified #' @param with indices of the factors against which others are considered conditionally independent #' @rdname loglin-utilities #' @export conditional <- function(nf, table=NULL, factors=1:nf, with=nf) { if (!is.null(table)) factors <- names(dimnames(table)) if (nf == 1) return (list(term1=factors[1])) if (nf == 2) return (list(term1=factors[1], term2=factors[2])) main <- setdiff(1:nf, with) others <- matrix(factors[with], length(with), length(main)) result <- rbind(factors[main], others) result <- as.list(as.data.frame(result, stringsAsFactors=FALSE)) names(result) <- paste('term', 1:length(result), sep='') result } #' models of mutual independence of all factors #' @param nf number of factors for which to generate model #' @param table a contingency table used for factor names, typically the output from \code{\link[base]{table}} #' @param factors names of factors used in the model when \code{table} is not specified #' @rdname loglin-utilities #' @export mutual <- function(nf, table=NULL, factors=1:nf) { if (!is.null(table)) factors <- names(dimnames(table)) result <- sapply(factors[1:nf], list) names(result) <- paste('term', 1:length(result), sep='') result } #' saturated model: highest-order interaction #' @param nf number of factors for which to generate model #' @param table a contingency table used for factor names, typically the output from \code{\link[base]{table}} #' @param factors names of factors used in the model when \code{table} is not specified #' @rdname loglin-utilities #' @export saturated <- function(nf, table=NULL, factors=1:nf) { if (!is.null(table)) factors <- names(dimnames(table)) list(term1=factors[1:nf]) } # models of conditional independence, given one pair of variables ## Not needed: handled by condit, with length(with)>1 #condit2 <- function(nf, factors=1:nf, with=1:2) { # if (nf == 1) return (list(term1=factors[1])) # if (nf == 2) return (list(term1=factors[1], term2=factors[2])) # others <- setdiff(1:nf, with) # result <- rbind(factors[with], cbind(factors[others], factors[others])) # result <- as.list(as.data.frame(result, stringsAsFactors=FALSE)) # names(result) <- paste('term', 1:length(result), sep='') # result #} #' markov models of a given order #' @param nf number of factors for which to generate model #' @param table a contingency table used for factor names, typically the output from \code{\link[base]{table}} #' @param factors names of factors used in the model when \code{table} is not specified #' @param order order of the markov chain #' @rdname loglin-utilities #' @export markov <- function(nf, factors=1:nf, order=1) { if (nf == 1) return (list(term1=factors[1])) if (nf == 2) return (list(term1=factors[1], term2=factors[2])) if (length(factors) < order+2) { warning(paste('Not enough factors for order', order, 'Markov chain; using order=1')) order <-1 result <- rbind(factors[1:(nf-1)], factors[2:nf]) } else { if (nf <= order+1) result <- factors[1:nf] else { result <- NULL for (i in 1:(order+1)) result <- rbind(result, factors[i:(nf-order+i-1)]) } } result <- as.list(as.data.frame(result, stringsAsFactors=FALSE)) names(result) <- paste('term', 1:length(result), sep='') result } #' convert a loglin model to a model formula for loglm #' @param x a list of terms in a loglinear model, such as returned by \code{joint}, \code{conditional}, \dots #' @param env environment in which to evaluate the formula #' @source Code from Henrique Dallazuanna, <[email protected]>, R-help 7-4-2013 #' @rdname loglin-utilities #' @export loglin2formula <- function(x, env = parent.frame()) { terms <- lapply(x, paste, collapse = ":") formula(sprintf(" ~ %s", do.call(paste, c(terms, sep = "+"))), env=env) } #' convert a loglin model to a string, using bracket notation for the high-order terms #' @param x a list of terms in a loglinear model, such as returned by \code{joint}, \code{conditional}, \dots #' @param brackets characters to use to surround model terms. Either a single character string containing two characters #' or a character vector of length two. #' @param sep characters used to separate factor names within a term #' @param collapse characters used to separate terms #' @param abbrev #' @rdname loglin-utilities #' @export loglin2string <- function(x, brackets = c('[', ']'), sep=',', collapse=' ', abbrev) { if (length(brackets)==1 && (nchar(brackets)>1)) brackets <- unlist(strsplit(brackets, "")) terms <- lapply(x, paste, collapse=sep) terms <- paste(brackets[1], terms, brackets[2], sep='') paste(terms, collapse= ' ') }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/loglin-utilities.R
## Original from gmlss.dist ## I think this is working correctly 01/03/10 #LG <- function (mu.link = "logit") #{ # mstats <- checklink("mu.link", "LG", substitute(mu.link),c("logit", "probit", "cloglog", "cauchit", "log", "own")) # structure( # list(family = c("LG", "Logarithmic"), # parameters = list(mu = TRUE), # the mean # nopar = 1, # type = "Discrete", # mu.link = as.character(substitute(mu.link)), # mu.linkfun = mstats$linkfun, # mu.linkinv = mstats$linkinv, # mu.dr = mstats$mu.eta, # dldm = function(y,mu) (y/mu)+1/((1-mu)*log(1-mu)), # d2ldm2 = function(y,mu) # { # dldm <- (y/mu)+1/((1-mu)*log(1-mu)) # d2ldm2 <- -dldm^2 # d2ldm2 # }, # G.dev.incr = function(y,mu,...) -2*dLG(x = y, mu = mu, log = TRUE), # rqres = expression(rqres(pfun="pLG", type="Discrete", ymin=1, y=y, mu=mu)), # mu.initial =expression({mu <- 0.9 } ), # mu.valid = function(mu) all(mu > 0 & mu < 1), # y.valid = function(y) all(y > 0) # ), # class = c("gamlss.family","family")) #} #----------------------------------------------------------------------------------------- dlogseries<-function(x, prob = 0.5, log = FALSE) { if (any(prob <= 0) | any(prob >= 1) ) stop(paste("prob must be greater than 0 and less than 1", "\n", "")) if (any(x <= 0) ) stop(paste("x must be >0", "\n", "")) logfy <- x*log(prob)-log(x)-log(-log(1-prob)) if(log == FALSE) fy <- exp(logfy) else fy <- logfy fy } #---------------------------------------------------------------------------------------- plogseries <- function(q, prob = 0.5, lower.tail = TRUE, log.p = FALSE) { if (any(prob <= 0) | any(prob >= 1) ) stop(paste("prob must be greater than 0 and less than 1", "\n", "")) if (any(q <= 0) ) stop(paste("q must be >0", "\n", "")) ly <- length(q) FFF <- rep(0,ly) nmu <- rep(prob, length = ly) j <- seq(along=q) for (i in j) { y.y <- q[i] mm <- nmu[i] allval <- seq(1,y.y) pdfall <- dlogseries(allval, prob = mm, log = FALSE) FFF[i] <- sum(pdfall) } cdf <- FFF cdf <- if(lower.tail==TRUE) cdf else 1-cdf cdf <- if(log.p==FALSE) cdf else log(cdf) cdf } #---------------------------------------------------------------------------------------- qlogseries <- function(p, prob=0.5, lower.tail = TRUE, log.p = FALSE, max.value = 10000) { if (any(prob <= 0) | any(prob >= 1) ) stop(paste("prob must be greater than 0 and less than 1", "\n", "")) if (any(p < 0) | any(p > 1.0001)) stop(paste("p must be between 0 and 1", "\n", "")) if (log.p==TRUE) p <- exp(p) else p <- p if (lower.tail==TRUE) p <- p else p <- 1-p ly <- length(p) QQQ <- rep(0,ly) nmu <- rep(prob, length = ly) for (i in seq(along=p)) { cumpro <- 0 if (p[i]+0.000000001 >= 1) QQQ[i] <- Inf else { for (j in seq(from = 1, to = max.value)) { cumpro <- plogseries(j, prob = nmu[i], log.p = FALSE) QQQ[i] <- j if (p[i] <= cumpro ) break } } } QQQ } #---------------------------------------------------------------------------------------- rlogseries <- function(n, prob = 0.5) { if (any(prob <= 0) | any(prob >= 1) ) stop(paste("prob must be greater than 0 and less than 1", "\n", "")) if (any(n <= 0)) stop(paste("n must be a positive integer", "\n", "")) n <- ceiling(n) p <- runif(n) r <- qlogseries(p, prob=prob) r } #----------------------------------------------------------------------------------------
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/logseries.R
#' --- #' title: "Custom plot function for mjca" #' date: "28 Jan 2016" #' --- #' #' #' @param obj An \code{"mjca"} object #' @param map Character string specifying the map type. Allowed options include #' \code{"symmetric"} (default), #' \code{"rowprincipal"}, \code{"colprincipal"}, \code{"symbiplot"}, #' \code{"rowgab"}, \code{"colgab"}, \code{"rowgreen"}, \code{"colgreen"} #' @param dim Dimensions to plot, a vector of length 2. #' @param col Vector of colors, one for each factor in the MCA #' @param pch Vector of point symbols for the category levels, one for each factor #' @param cex Character size for points and level labels #' @param pos Position of level labels relative to the category points; either a single number #' or a vector of length equal to the number of category points. #' @param lines A logical or an integer vector indicating which factors are to be #' joined with lines using \code{\link{multilines}} #' @param lwd Line width(s) for the lines #' @param legend Logical; draw a legend for the factor names? #' @param legend.pos Position of the legend in the plot #' @param xlab,ylab Labels for horizontal and vertical axes. The default, \code{"_auto_" } #' means that the function auto-generates a label of the form \code{Dimension X (xx.x %)} #' @param rev.axes A logical vector of length 2, where TRUE reverses the direction of the #' corresponding axis. #' @param ... Arguments passed down to \code{plot} #' @return Returns the coordinates of the category points invisibly #' #' @author Michael Friendly #' @seealso \code{\link{plot.mjca}} #' @examples #' data(Titanic) #' titanic.mca <- ca::mjca(Titanic) #' mcaplot(titanic.mca, legend=TRUE, legend.pos="topleft") #' #' data(HairEyeColor) #' haireye.mca <- ca::mjca(HairEyeColor) #' mcaplot(haireye.mca, legend=TRUE, cex.lab=1.3) mcaplot <- function(obj, map="symmetric", dim=1:2, col=c("blue", "red", "brown", "black", "green3", "purple"), pch=15:20, cex=1.2, pos=3, lines=TRUE, lwd=2, legend=FALSE, legend.pos="topright", xlab = "_auto_", ylab = "_auto_", rev.axes = c(FALSE, FALSE), ...) { if(!requireNamespace("ca", quietly=TRUE)) stop("The ca package is required") if(!inherits(obj, "mjca")) stop("Only defined for mjca objects") coords <- cacoord(obj, type=map, rows=FALSE) coords <- data.frame(coords, obj$factors) # extract factor names & levels nlev <- obj$levels.n nfac <- length(nlev) pch <- rep_len(pch, nfac) col <- rep_len(col, nfac) lwd <- rep_len(lwd, nfac) rev.axes <- rep(rev.axes, length.out=2) if(any(dim > ncol(coords))) stop("dim must be valid dimensions of the coordinates") labs <- pctlab(obj) if (xlab == "_auto_") xlab <- labs[dim[1]] if (ylab == "_auto_") ylab <- labs[dim[2]] if(isTRUE(rev.axes[1])) coords[, dim[1]] <- -coords[, dim[1]] if(isTRUE(rev.axes[2])) coords[, dim[2]] <- -coords[, dim[2]] plot(coords[, dim], type='n', asp=1, xlab=xlab, ylab=ylab, ...) points(coords[,dim], pch=rep(pch, nlev), col=rep(col, nlev), cex=cex) text(coords[,dim], labels=coords$level, col=rep(col, nlev), pos=pos, cex=cex, xpd=TRUE) if (is.logical(lines)) lines <- if(lines) 1:nfac else NULL if(length(lines)) multilines(coords[, dim], group=coords$factor, which=lines, col=col, lwd=lwd) abline(h = 0, v = 0, lty = "longdash", col="gray") if (legend) { factors <- coords$factor factors <- factors[!duplicated(factors)] legend(legend.pos, legend=factors, title="Factor", title.col="black", col=col, text.col=col, pch=pch, bg=rgb(.95, .95, .95, .3), cex=cex) } invisible(coords) } pctlab <- function(obj, prefix="Dimension ", decimals=1) { values <- obj$sv^2 if (obj$lambda == "JCA"){ pct <- rep_len(NA, length(values)) } else { if (obj$lambda == "adjusted") { values <- obj$inertia.e pct <- round(100 * values, decimals) } else { pct <- round(100 * values / sum(values), decimals) } } pctval <- ifelse(is.na(pct), NULL, paste0(" (", pct, "%)")) paste0(prefix, 1:length(values), pctval) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/mcaplot.R
## ## One-line summary of model fit for a glm/loglm object ## `modFit` <- function(x, ...) UseMethod("modFit") modFit.glm <- function(x, stats="chisq", digits=2, ...) { if (!inherits(x,"glm")) stop("modFit requires a glm object") result <- NULL if ("chisq" %in% stats) result <- paste("G^2(",x$df.residual,")=", formatC(x$deviance,digits=digits,format="f"),sep="") if ("aic" %in% stats) result <- paste(result, " AIC=", formatC(x$aic,digits=digits,format="f"),sep="") result } modFit.loglm <- function(x, stats="chisq", digits=2, ...) { if (!inherits(x,"loglm")) stop("modFit requires a loglm object") result <- NULL if ("chisq" %in% stats) result <- paste("G^2(",x$df,")=", formatC(x$deviance,digits=digits,format="f"),sep="") if ("aic" %in% stats) { aic<-x$deviance-x$df*2 result <- paste(result, " AIC=", formatC(aic,digits=digits,format="f"),sep="") } result }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/modFit.R
# mosaic plot for a glm object # Allow it to use residuals of any type computed by residuals() # or to pass residuals calculated by another function, e.g., rstandard(), rstudent() # # Allow to apply to any model with discrete factors # last modified: 3/6/2009 1:51PM # - fixed buggy version using ideas from vcd:::plot.loglm # - now use $data component when it is a table ## TODO: move to utility.R #is.discrete.model <- function(model) # all(attr(terms(model), "dataClasses")[-1] %in% c("factor", "ordered")) `mosaic.glm` <- function(x, formula = NULL, panel=mosaic, type=c("observed", "expected"), residuals=NULL, residuals_type = c("pearson", "deviance", "rstandard"), gp = shading_hcl, gp_args = list(), ...) { #require(vcd) if (!inherits(x,"glm")) stop("mosaic.glm requires a glm object") df.residual <- x$df.residual observed <- x$data if (is.null(formula) && inherits(observed, "table")) formula <- reformulate(names(dimnames(observed))) if (is.null(formula)) { if (is.environment(observed)) observed <- model.frame(x) else { if (!is.null(x$call$subset)) observed <- subset(observed, eval(x$call$subset, observed)) if (!is.null(x$na.action)) observed <- observed[-x$na.action,] } ## get all factors excluding response factors <- sapply(observed, inherits, "factor") resp <- as.character(x$formula[[2]]) factors <- observed[setdiff(colnames(observed[factors]), resp)] ## drop unused levels for(nm in names(factors)) { f <- factors[[nm]] if(is.factor(f) && length(unique(f[!is.na(f)])) < length(levels(f))) factors[[nm]] <- factors[[nm]][, drop = TRUE] } ok <- TRUE ## check cross-classifying if (ok <- isTRUE(all(table(factors) == 1))) { warning("no formula provided, assuming ", deparse(formula(terms(~ . , data = factors))), "\n", call. = FALSE) } if (!ok) stop("cannot identify indexing factors from ", substitute(x), "$data - please provide formula", call. = FALSE) } else { if (length(formula) == 3) formula <- formula[-2] ## get indexing factors allowing for missing data, subset etc factors <- do.call("model.frame", list(formula = formula, data = observed, subset = x$call$subset, na.action = na.pass, drop.unused.levels = TRUE)) ## following loop needed due to bug in model.frame.default (fixed for R 2.12) for(nm in names(factors)) { f <- factors[[nm]] if(is.factor(f) && length(unique(f[!is.na(f)])) < length(levels(f))) factors[[nm]] <- factors[[nm]][, drop = TRUE] } if (!is.null(x$na.action)) factors <- factors[-x$na.action,] } if (x$family$family == "poisson") { observed <- as.table(tapply(x$y, factors, sum)) expected <- as.table(tapply(fitted(x), factors, sum)) } else{ observed <- as.table(tapply(x$prior.weights, factors, sum)) expected <- as.table(tapply(x$prior.weights * x$weights, factors, sum)) } ## replace any missing values with zero observed[is.na(observed)] <- 0 #else strucplot would do this expected[is.na(expected)] <- 0 type <- match.arg(tolower(type), c("observed", "expected")) if (any(observed < 0, na.rm = TRUE)) stop("requires a non-negative response vector") ## reshape the residuals to conform to the structure of data ## if max one residual per cell, use residuals_type if (max(table(factors)) == 1) { residuals_type <- match.arg(tolower(residuals_type), c("pearson", "deviance", "rstandard")) if (missing(residuals)) residuals <- if (residuals_type=="rstandard") rstandard(x) else residuals(x, type=residuals_type) residuals <- as.table(tapply(residuals, factors, sum)) df <- x$df.residual } ## for marginal views, use aggregated working residuals else { residuals <- meanResiduals(x, factors) residuals_type <- "working" #what is this used for? df <- attr(residuals, "df") if (df == 0) { warning("There are zero degrees of freedom ", "for the test of normality") df <- NA } } ## replace any missing values with zero residuals[is.na(residuals)] <- 0 gp <- if (inherits(gp, "grapcon_generator")) do.call("gp", c(list(observed, residuals, expected, df), as.list(gp_args))) else gp panel(observed, residuals=residuals, expected=expected, type=type, residuals_type=residuals_type, gp=gp, ...) } ## convenience functions for sieve and assoc plots sieve.glm <- function (x, ...) { mosaic(x, panel = sieve, ...) } assoc.glm <- function (x, ...) { mosaic(x, panel = assoc, ...) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/mosaic.glm.R
#' Mosaic Displays for a glmlist Object #' @param x a glmlist object #' @param selection the index or name of one glm in \code{x} #' @param panel panel function #' @param type a character string indicating whether the \code{"observed"} or the \code{"expected"} values of the table should be visualized #' @param legend show a legend in the mosaic displays? #' @param main either a logical, or a vector of character strings used for plotting the main title. If main is a logical and TRUE, the name of the selected glm object is used #' @param ask should the function display a menu of models, when one is not specified in \code{selection}? #' @param graphics use a graphic menu when \code{ask=TRUE}? #' @param rows,cols when \code{ask=FALSE}, the number of rows and columns in which to plot the mosaics #' @param newpage start a new page? (only applies to \code{ask=FALSE}) #' @param ... other arguments passed to \code{\link{mosaic.glm}} #' @export mosaic.glmlist <- function(x, selection, panel=mosaic, type=c("observed", "expected"), legend=ask | !missing(selection), main=NULL, ask=TRUE, graphics=TRUE, rows, cols, newpage=TRUE, ...) { # calls <- sapply(x, mod.call) # get model calls as strings models <- names(x) if (!is.null(main)) { if (is.logical(main) && main) main <- models } else main <- rep(main, length(x)) type=match.arg(type) if (!missing(selection)){ if (is.character(selection)) selection <- gsub(" ", "", selection) return(panel(x[[selection]], type=type, main=main[selection], legend=legend, ...)) } # perhaps make these model labels more explicit for the menu if (ask & interactive()){ repeat { selection <- menu(models, graphics=graphics, title="Select Model to Plot") if (selection == 0) break else panel(x[[selection]], type=type, main=main[selection], legend=legend, ...) } } else { nmodels <- length(x) mfrow <- mfrow(nmodels) if (missing(rows) || missing(cols)){ rows <- mfrow[1] cols <- mfrow[2] } if (newpage) grid.newpage() lay <- grid.layout(nrow=rows, ncol = cols) pushViewport(viewport(layout = lay, y = 0, just = "bottom")) for (i in 1:rows) { for (j in 1:cols){ if ((sel <-(i-1)*cols + j) > nmodels) break pushViewport(viewport(layout.pos.row=i, layout.pos.col=j)) panel(x[[sel]], type=type, main=main[sel], newpage=FALSE, legend=legend, ...) popViewport() } } } } mosaic.loglmlist <- function(x, selection, panel=mosaic, type=c("observed", "expected"), legend=ask | !missing(selection), main=NULL, ask=TRUE, graphics=TRUE, rows, cols, newpage=TRUE, ...) { models <- names(x) strings <- as.vector(sapply(x, function(x) x$model.string)) if (!is.null(main)) { if (is.logical(main) && main) main <- ifelse(as.vector(sapply(strings, is.null)), models, strings) } else main <- rep(main, length(x)) type=match.arg(type) if (!missing(selection)){ if (is.character(selection)) selection <- gsub(" ", "", selection) return(panel(x[[selection]], type=type, main=main[selection], legend=legend, ...)) } # perhaps make these model labels more explicit for the menu if (ask & interactive()){ repeat { selection <- menu(models, graphics=graphics, title="Select Model to Plot") if (selection == 0) break else panel(x[[selection]], type=type, main=main[selection], legend=legend, ...) } } else { nmodels <- length(x) mfrow <- mfrow(nmodels) if (missing(rows) || missing(cols)){ rows <- mfrow[1] cols <- mfrow[2] } if (newpage) grid.newpage() lay <- grid.layout(nrow=rows, ncol = cols) pushViewport(viewport(layout = lay, y = 0, just = "bottom")) for (i in 1:rows) { for (j in 1:cols){ if ((sel <-(i-1)*cols + j) > nmodels) break pushViewport(viewport(layout.pos.row=i, layout.pos.col=j)) panel(x[[sel]], type=type, main=main[sel], newpage=FALSE, legend=legend, ...) popViewport() } } } } # from effects::utilities.R mfrow <- function(n, max.plots=0){ # number of rows and columns for array of n plots if (max.plots != 0 & n > max.plots) stop(paste("number of plots =",n," exceeds maximum =", max.plots)) rows <- round(sqrt(n)) cols <- ceiling(n/rows) c(rows, cols) } # from plot.lm: get model call as a string # TODO: should use abbreviate() mod.call <- function(x) { cal <- x$call if (!is.na(m.f <- match("formula", names(cal)))) { cal <- cal[c(1, m.f)] names(cal)[2L] <- "" } cc <- deparse(cal, 80) nc <- nchar(cc[1L], "c") abbr <- length(cc) > 1 || nc > 75 cap <- if (abbr) paste(substr(cc[1L], 1L, min(75L, nc)), "...") else cc[1L] cap }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/mosaic.glmlist.R
##################################### ## Produce a 3D mosaic plot using rgl ##################################### # TODO: provide formula interface # TODO: handle zero margins (causes display to be erased in shapelist3d) # DONE: handle zero cells # DONE: generalize the calculation of residuals # DONE: allow display of type=c("observed", "expected") # DONE: if ndim>3, provide for labels at max or min # DONE: make object oriented and provide a loglm method # mosaic3d: provide observed array of counts and either residuals, expected frequencies, # or a loglin set of margins to fit mosaic3d <- function(x, ...) { UseMethod("mosaic3d") } mosaic3d.loglm <- function (x, type = c("observed", "expected"), residuals_type = c("pearson", "deviance"), # gp = shading_hcl, gp_args = list(), ...) { residuals_type <- match.arg(tolower(residuals_type), c("pearson", "deviance")) if (is.null(x$fitted)) x <- update(x, fitted = TRUE) expected <- fitted(x) residuals <- residuals(x, type = "pearson") observed <- residuals * sqrt(expected) + expected if (residuals_type == "deviance") residuals <- residuals(x, type = "deviance") # gp <- if (inherits(gp, "grapcon_generator")) # do.call("gp", c(list(observed, residuals, expected, x$df), # as.list(gp_args))) # else gp mosaic3d.default(observed, residuals = residuals, expected = expected, type = type, residuals_type = residuals_type, # gp = gp, ...) } mosaic3d.default <- function(x, expected=NULL, residuals=NULL, type = c("observed", "expected"), residuals_type = NULL, shape=rgl::cube3d(alpha=alpha), alpha=0.5, spacing=0.1, split_dir=1:3, shading=shading_basic, interpolate=c(2,4), zero_size=.05, label_edge, labeling_args=list(), newpage=TRUE, box=FALSE, ...) { if (!requireNamespace("rgl")) stop("rgl is required") type <- match.arg(type) if (is.null(residuals)) { residuals_type <- if (is.null(residuals_type)) "pearson" else match.arg(tolower(residuals_type), c("pearson", "deviance", "ft")) } ## convert structable object if (is.structable(x)) { x <- as.table(x) } ## table characteristics levels <- dim(x) ndim <- length(levels) dn <- dimnames(x) if (is.null(dn)) dn <- dimnames(x) <- lapply(levels, seq) vnames <- names(dimnames(x)) if (is.null(vnames)) vnames <- names(dn) <- names(dimnames(x)) <- LETTERS[1:ndim] ## replace NAs by 0 if (any(nas <- is.na(x))) x[nas] <- 0 ## model fitting: ## calculate expected if needed if ((is.null(expected) && is.null(residuals)) || !is.numeric(expected)) { if (inherits(expected, "formula")) { fm <- loglm(expected, x, fitted = TRUE) expected <- fitted(fm) df <- fm$df } else { if (is.null(expected)) expected <- as.list(1:ndim) fm <- loglin(x, expected, fit = TRUE, print = FALSE) expected <- fm$fit df <- fm$df } } ## compute residuals if (is.null(residuals)) residuals <- switch(residuals_type, pearson = (x - expected) / sqrt(ifelse(expected > 0, expected, 1)), deviance = { tmp <- 2 * (x * log(ifelse(x == 0, 1, x / ifelse(expected > 0, expected, 1))) - (x - expected)) tmp <- sqrt(pmax(tmp, 0)) ifelse(x > expected, tmp, -tmp) }, ft = sqrt(x) + sqrt(x + 1) - sqrt(4 * expected + 1) ) ## replace NAs by 0 if (any(nas <- is.na(residuals))) residuals[nas] <- 0 # switch observed and expected if required observed <- if (type == "observed") x else expected expected <- if (type == "observed") expected else x # replicate arguments to number of dimensions spacing <- rep(spacing, length=ndim) split_dir <- rep(split_dir, length=ndim) if(missing(label_edge)) label_edge <- rep( c('-', '+'), each=3, length=ndim) zeros <- observed <= .Machine$double.eps shapelist <- shape # sanity check if (!inherits(shapelist, "shape3d")) stop("shape must be a shape3d object") if (newpage) rgl::open3d() for (k in 1:ndim) { marg <- margin.table(observed, k:1) if (k==1) { shapelist <- split3d(shapelist, marg, split_dir[k], space=spacing[k]) label3d(shapelist, split_dir[k], dn[[k]], vnames[k], edge=label_edge[k], ...) } else { marg <- matrix(marg, nrow=levels[k]) shapelist <- split3d(shapelist, marg, split_dir[k], space=spacing[k]) names(shapelist) <- apply(as.matrix(expand.grid(dn[1:k])), 1, paste, collapse=":") L <- length(shapelist) label_cells <- if (label_edge[k]=='-') 1:levels[k] else (L-levels[k]+1):L label3d(shapelist[label_cells], split_dir[k], dn[[k]], vnames[k], edge=label_edge[k], ...) } } # assign colors # TODO: allow alpha to control transparency of side walls col <- shading(residuals, interpolate=interpolate) # display, but exclude the zero cells rgl::shapelist3d(shapelist[!as.vector(zeros)], col=col[!as.vector(zeros)], ...) # plot markers for zero cells if (any(zeros)) { ctrs <- t(sapply(shapelist, center3d)) rgl::spheres3d(ctrs[as.vector(zeros),], radius=zero_size) } # invisible(structable(observed)) invisible(shapelist) } # basic shading_Friendly, adapting the simple code used in mosaicplot() shading_basic <- function(residuals, interpolate=TRUE) { if (is.logical(interpolate)) interpolate <- c(2, 4) else if (any(interpolate <= 0) || length(interpolate) > 5) stop("invalid 'interpolate' specification") shade <- sort(interpolate) breaks <- c(-Inf, -rev(shade), 0, shade, Inf) colors <- c(hsv(0, s = seq.int(1, to = 0, length.out = length(shade) + 1)), hsv(4/6, s = seq.int(0, to = 1, length.out = length(shade) + 1))) colors[as.numeric(cut(residuals, breaks))] } # provide labels for 3D objects below/above their extent along a given dimension # FIXME: kludge for interline gap between level labels and variable name # TODO: how to pass & extract labeling_args, e.g., labeling_args=list(at='min', fontsize=10) label3d <- function(objlist, dim, text, varname, offset=.05, adj, edge="-", gap=.1, labeling_args, ...) { if(missing(adj)) { if (dim < 3) adj <- ifelse(edge == '-', c(0.5, 1), c(0.5, 0)) else adj <- ifelse(edge == '-', c(1, 0.5), c(0, 0.5)) } ranges <- lapply(objlist, range3d) loc <- t(sapply(ranges, colMeans)) # positions of labels on dimension dim min <- t(sapply(ranges, function(x) x[1,])) # other dimensions at min values max <- t(sapply(ranges, function(x) x[2,])) # other dimensions at max values xyz <- if (edge == '-') (min - offset) else (max + offset) xyz[,dim] <- loc[,dim] if(!missing(varname)) { loclab <- colMeans(loc) # NB: doesn't take space into acct xyzlab <- if (edge == '-') min[1,] - offset - gap else max[1,] + offset + gap xyzlab[dim] <- loclab[dim] xyz <- rbind(xyz, xyzlab) text <- c(text, varname) } result <- c(labels = rgl::texts3d(xyz, texts=text, adj=adj, ...)) invisible(result) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/mosaic3d.R
# Print method for Kappa: Add a column showing z values ## DONE: now set digits ## DONE: now include CI print.Kappa <- function (x, digits=max(getOption("digits") - 3, 3), CI=FALSE, level=0.95, ...) { tab <- rbind(x$Unweighted, x$Weighted) z <- tab[,1] / tab[,2] tab <- cbind(tab, z) if (CI) { q <- qnorm((1 + level)/2) lower <- tab[,1] - q * tab[,2] upper <- tab[,1] + q * tab[,2] tab <- cbind(tab, lower, upper) } rownames(tab) <- names(x)[1:2] print(tab, digits=digits, ...) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/print.Kappa.R
#' Sequential loglinear models for an n-way table #' This function takes an n-way contingency table and fits a series of sequential #' models to the 1-, 2-, ... n-way marginal tables, corresponding to a variety of #' types of loglinear models. #' @param x a contingency table in array form, with optional category labels specified in the dimnames(x) attribute, #' or else a data.frame in frequency form, with the frequency variable names "Freq". #' @param type type of sequential model to fit #' @param marginals which marginals to fit? #' @param vorder order of variables #' @param k indices of conditioning variable(s) for "joint", "conditional" or order for "markov" #' @param prefix #' @param fitted keep fitted values? seq_loglm <- function( x, type = c("joint", "conditional", "mutual", "markov", "saturated"), marginals = 1:nf, # which marginals to fit? vorder = 1:nf, # order of variables in the sequential models k = NULL, # conditioning variable(s) for "joint", "conditional" or order for "markov" prefix = 'model', fitted = TRUE, # keep fitted values? ... ) { if (inherits(x, "data.frame") && "Freq" %in% colnames(x)) { x <- xtabs(Freq ~ ., data=x) } if (!inherits(x, c("table", "array"))) stop("not an xtabs, table, array or data.frame with a 'Freq' variable") nf <- length(dim(x)) x <- aperm(x, vorder) factors <- names(dimnames(x)) indices <- 1:nf type = match.arg(type) # models <- as.list(rep(NULL, length(marginals))) models <- list() for (i in marginals) { mtab <- margin.table(x, 1:i) if (i==1) { # KLUDGE: use loglin, but try to make it look like a loglm object mod <- loglin(mtab, margin=NULL, print=FALSE) mod$model.string = paste("=", factors[1]) mod$margin <- list(factors[1]) # mod$margin <- names(dimnames(mtab)) # names(mod$margin) <- factors[1] if (fitted) { fit <- mtab fit[] <- (sum(mtab) / length(mtab)) mod$fitted <- fit } mod$nobs <- length(mtab) mod$frequencies <- mtab mod$deviance <- mod$lrt class(mod) <- c("loglin", "loglm") } else { expected <- switch(type, 'conditional' = conditional(i, mtab, with=if(is.null(k)) i else k), 'joint' = joint(i, mtab, with=if(is.null(k)) i else k), 'mutual' = mutual(i, mtab), 'markov' = markov(i, mtab, order=if(is.null(k)) 1 else k), 'saturated' = saturated(i, mtab) ) form <- loglin2formula(expected) # mod <- loglm(formula=form, data=mtab, fitted=TRUE) mod <- eval(bquote(MASS::loglm(.(form), data=mtab, fitted=fitted))) mod$model.string <- loglin2string(expected, brackets=if (i<nf) '()' else '[]') } # cat(i, " model.string: ", mod$model.string, "\n") # cat("model:\n"); print(mod) models[[i]] <- mod } names(models) <- paste(prefix, '.', indices, sep='') models <- models[marginals] class(models) <- "loglmlist" invisible(models) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/seq_loglm.R
#' Sequential Mosaics and Strucplots for an N-way Table #' This function takes an n-way contingency table and plots mosaics for series of sequential #' models to the 1-, 2-, ... n-way marginal tables, corresponding to a variety of #' types of loglinear models. #' @param x a contingency table in array form, with optional category labels specified in the dimnames(x) attribute, #' or else a data.frame in frequency form, with the frequency variable names "Freq". #' @param panel panel function #' @param type type of sequential model to fit #' @param plots which marginals to plot? #' @param vorder order of variables #' @param k indices of conditioning variable(s) for "joint", "conditional" or order for "markov" #' @export seq_mosaic <- function( x, panel = mosaic, type = c("joint", "conditional", "mutual", "markov", "saturated"), plots = 1:nf, # which plots to produce? vorder = 1:nf, # order of variables in the sequential plots k = NULL, # conditioning variable(s) for "joint", "conditional" or order for "markov" ... ) { if (inherits(x, "data.frame") && "Freq" %in% colnames(x)) { x <- xtabs(Freq ~ ., data=x) } if (!inherits(x, c("table", "array"))) stop("not an xtabs, table, array or data.frame with a 'Freq' variable") nf <- length(dim(x)) x <- aperm(x, vorder) factors <- names(dimnames(x)) indices <- 1:nf type = match.arg(type) for (i in plots) { mtab <- margin.table(x, 1:i) df <- NULL if (i==1) { expected <- mtab expected[] <- sum(mtab) / length(mtab) df <- length(mtab)-1 model.string = paste("=", factors[1]) } else { expected <- switch(type, 'conditional' = conditional(i, mtab, with=if(is.null(k)) i else k), 'joint' = joint(i, mtab, with=if(is.null(k)) i else k), 'mutual' = mutual(i, mtab), 'markov' = markov(i, mtab, order=if(is.null(k)) 1 else k), 'saturated' = saturated(i, mtab) ) model.string <- loglin2string(expected, brackets=if (i<nf) '()' else '[]') } panel(mtab, expected=expected, df=df, main=model.string, ...) } }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/seq_mosaic.R
# split a 3D object along dimension dim, according to the proportions or # frequencies specified in vector p split3d <- function(obj, ...) { UseMethod("split3d") } split3d.shape3d <- function(obj, p, dim, space=.10, ...) { range <-range3d(obj) min <- range[1,] p <- p/sum(p) # assure proportions uspace <- space/(length(p)-1) # unit space between objects scales <- p * (1-space) shifts <- c(0, cumsum(p)[-length(p)])*diff(range[,dim]) result <- list() for (i in seq_along(p)) { xscale <- yscale <- zscale <- 1 xshift <- yshift <- zshift <- 0 if (dim == 1 || tolower(dim)=='x') { xscale <- scales[i] xshift <- shifts[i] + min[1]*(1-xscale) + (uspace * (i-1)) } else if (dim == 2|| tolower(dim)=='y') { yscale <- scales[i] yshift <- shifts[i] + min[2]*(1-yscale) + (uspace * (i-1)) } else if (dim == 3|| tolower(dim)=='y') { zscale <- scales[i] zshift <- shifts[i] + min[3]*(1-zscale) + (uspace * (i-1)) } result[[i]] <- rgl::translate3d(rgl::scale3d(obj, xscale, yscale, zscale), xshift, yshift, zshift) } result } # split a list of 3D objects, according to the proportions specified in # the columns of p. split3d.list <- function(obj, p, dim, space=.10, ...) { nl <- length(obj) if (!is.matrix(p) || ncol(p) != nl) stop(gettextf("p must be a matrix with %i columns", nl)) sl <- list() for (i in seq_along(obj)) { sl <- c(sl, split3d(obj[[i]], p[,i], dim=dim, space=space)) } sl } #range3d <- function(obj, ...) { # UseMethod("range3d") #} range3d <- function(obj) { if (!"vb" %in% names(obj)) stop("Not a mesh3d or shape3d object") x <- with(obj, range(vb[1,]/vb[4,])) y <- with(obj, range(vb[2,]/vb[4,])) z <- with(obj, range(vb[3,]/vb[4,])) result <- cbind(x,y,z) rownames(result)<- c('min', 'max') result } center3d <- function(obj) { range <-range3d(obj) colMeans(range) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/split3d.R
# summarise a glm object or glmlist summarise <- function(...) { .Deprecated("LRstats") LRstats(...) } # summarise <- function(object, ...) { # UseMethod("summarise") # } # # stat.summarise <- function(deviance, df, onames, n) { # p <- pchisq(deviance, df, lower.tail=FALSE) # aic <- deviance - 2*df # if (missing(n)) { # result <- data.frame(aic, deviance, df, p) # names(result) <- c("AIC", "LR Chisq", "Df", "Pr(>Chisq)") # } # else { # bic <- deviance - log(n)*df # result <- data.frame(aic, bic, deviance, df, p) # names(result) <- c("AIC", "BIC", "LR Chisq", "Df", "Pr(>Chisq)") # } # # rownames(result) <- onames # attr(result, "heading") <- "Model Summary:" # class(result) <- c("anova", "data.frame") # result # } # # # summarise.glm <-function(object, ..., test=NULL){ # dotargs <- list(...) # is.glm <- unlist(lapply(dotargs, function(x) inherits(x, "glm"))) # dotargs <- dotargs[is.glm] # if (length(dotargs)) # return(summarise.glmlist(c(list(object), dotargs), test = test)) # # oname <- as.character(sys.call())[2] # result <- stat.summarise(object$deviance, object$df.residual, oname, sum(fitted(object))) # result # } # # summarise.glmlist <-function(object, ..., test=NULL, sortby=NULL){ # nmodels <- length(object) # if (nmodels == 1) # return(summarise.glm(object[[1]], test = test)) # if (is.null(names(object))) { # oname <- as.character(sys.call())[-1] # oname <- oname[1:length(object)] # } # else oname <- names(object) # # resdf <- as.numeric(lapply(object, function(x) x$df.residual)) # resdev <- as.numeric(lapply(object, function(x) x$deviance)) # n <- as.numeric(lapply(object, function(x) sum(fitted(x)))) # result <- stat.summarise(resdev, resdf, oname, n) # if (!is.null(sortby)) { # result <- result[order(result[,sortby], decreasing=TRUE),] # } # result # } # # # summarise.loglm <-function(object, ...){ # dotargs <- list(...) # is.loglm <- unlist(lapply(dotargs, function(x) inherits(x, "loglm"))) # dotargs <- dotargs[is.loglm] # if (length(dotargs)) # return(summarise.loglmlist(c(list(object), dotargs))) # # oname <- as.character(sys.call())[2] # result <- stat.summarise(object$deviance, object$df, oname, sum(fitted(object))) # result # } # # summarise.loglmlist <-function(object, ..., sortby=NULL){ # nmodels <- length(object) # if (nmodels == 1) # return(summarise.loglm(object[[1]])) # if (is.null(names(object))) { # oname <- as.character(sys.call())[-1] # oname <- oname[1:length(object)] # } # else oname <- names(object) # # resdf <- as.numeric(lapply(object, function(x) x$df)) # resdev <- as.numeric(lapply(object, function(x) x$deviance)) # n <- as.numeric(lapply(object, function(x) sum(fitted(x)))) # result <- stat.summarise(resdev, resdf, oname, n) # if (!is.null(sortby)) { # result <- result[order(result[,sortby], decreasing=TRUE),] # } # result # } #
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/summarise-old.R
update.xtabs <- function (object, formula., ..., evaluate = TRUE) { if (is.null(call<-attr(object, "call"))) stop("need an object with call component") extras <- match.call(expand.dots = FALSE)$... if (!missing(formula.)) call$formula <- update.formula(call$formula, formula.) if (length(extras)) { existing <- !is.na(match(names(extras), names(call))) for (a in names(extras)[existing]) call[[a]] <- extras[[a]] if (any(!existing)) { call <- c(as.list(call), extras[!existing]) call <- as.call(call) } } if (evaluate) eval(call, parent.frame()) else call }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/update.xtabs.R
#summarise <- function (...) { # .Deprecated("summarise", package="vcdExtra") # LRstats(...) #} #
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/vcdExtra-deprecated.R
# Score test for zero inflation in Poisson data #https://stats.stackexchange.com/questions/118322/how-to-test-for-zero-inflation-in-a-dataset # References: # Broek, Jan van den. 1995. ?A Score Test for Zero Inflation in a Poisson Distribution.? Biometrics 51 (2): 738?43. doi:10.2307/2532959. # Yang, Zhao, James W. Hardin, and Cheryl L. Addy. 2010. ?Score Tests for Zero-Inflation in Overdispersed Count Data.? Communications in Statistics - Theory and Methods 39 (11): 2008?30. doi:10.1080/03610920902948228 # Van den Broek, J. (1995). A Score Test for Zero Inflation in a Poisson Distribution. Biometrics, 51(2), 738-743. doi:10.2307/2532959 zero.test <- function(x) { if(is.table(x)) { # expand to vector of values if(length(dim(x)) > 1) stop ("x must be a 1-way table") x <- rep(as.numeric(names(x)), unname(c(x))) } lambda <- mean(x) p0_tilde <- exp(-lambda) n0 <- sum(1*(!(x >0))) n <- length(x) numerator <- (n0 - n*p0_tilde)^2 denominator <- n*p0_tilde*(1-p0_tilde) - n*lambda*(p0_tilde^2) stat <- numerator/denominator pvalue <- pchisq(stat,df=1, ncp=0, lower.tail=FALSE) result <- list(statistic=stat, df=1, prob=pvalue) cat(paste("Score test for zero inflation\n\n", "\tChi-square =", round(stat,5), "\n", "\tdf = 1\n", "\tpvalue:", format.pval(pvalue), "\n")) invisible(result) }
/scratch/gouwar.j/cran-all/cranData/vcdExtra/R/zero.test.R
# Wong2-3 Political views and support for women to work library(vcdExtra) # Data from Wong, R. (2010), Association Models, Los Angeles: Sage, Number 07-164 # Table 2.3A, from the General Social Survey, 1998-2000. # Questions: # polviews: Think of self as liberal or conservative # fefam: Better for men to work and women to tend home Freq<-c(39, 50, 18, 4, 140,178, 85, 23, 108,195, 97, 23, 238,598,363,111, 78,250,150, 55, 50,200,208, 74, 8, 29, 46, 21) polviews<- gl(7,4) fefam <- gl(4,1,length=28) # create better labels for levels in mosaic() ## but, this screws up parameter names: use set_labels instead #polviews <- factor(polviews, labels=c("Lib++", "2", "3", "Moderate", "5", "6", "Cons++")) #fefam <- factor(fefam, labels=c("Dis+", "Dis", "Agr", "Agr+")) # long.vnames <- list(set_varnames = c(polviews="Political views", fefam="Females should tend home")) long.lnames <- list(polviews = c("Lib++", "2", "3", "Moderate", "5", "6", "Cons++"), fefam = c("Dis+", "Dis", "Agr", "Agr+")) # numeric versions for U, R, C, RC models Rscore<-as.numeric(polviews) Cscore<-as.numeric(fefam) # make a data frame Wong23 <- data.frame(Freq, polviews, fefam, Rscore, Cscore) #################################### # do a correspondence analysis first, to see the row/category relations Wong23.xtab <- xtabs(Freq ~ polviews+fefam, data=Wong23) dimnames(Wong23.xtab) <- long.lnames library(ca) plot(ca(Wong23.xtab)) title(main="Political views and support for women to work", xlab="Dim 1 (90.8%)", ylab="Dim 2 (8.5%)") #################################### ## OK now, gives warning Wong23.O <- gnm(Freq~polviews+fefam, family=poisson, data=Wong23) # OK, with formula mosaic(Wong23.O, main=paste("Independence model", modFit(Wong23.O)), formula=~polviews+fefam, labeling_args=long.vnames, set_labels=long.lnames) #################################### # Uniform association model Wong23.U<-gnm(Freq~polviews+fefam+Rscore:Cscore,family=poisson,tolerance = 1e-12, data=Wong23) anova(Wong23.U) # OK, w/o formula mosaic(Wong23.U, main=paste("Uniform association", modFit(Wong23.U)), formula=~polviews+fefam, labeling_args=long.vnames, set_labels=long.lnames) # display standardized residuals mosaic(Wong23.U, formula=~polviews+fefam, main=paste("Uniform association", modFit(Wong23.U)), labeling_args=long.vnames, set_labels=long.lnames, residuals_type="rstandard", labeling=labeling_residuals, suppress=1) # compare with gp=shading_Friendly) mosaic(Wong23.U, formula=~polviews+fefam, main=paste("Uniform association", modFit(Wong23.U)), labeling_args=long.vnames, set_labels=long.lnames, residuals_type="rstandard", labeling=labeling_residuals, suppress=1, gp=shading_Friendly) #################################### # Model B - R: Row Effects Wong23.R<-gnm(Freq~polviews+fefam+Cscore:polviews,family=poisson, data=Wong23) anova(Wong23.R) mosaic(Wong23.R, formula=~polviews+fefam, main="Row effects model", labeling_args=long.vnames, set_labels=long.lnames, residuals_type="rstandard", labeling=labeling_residuals, suppress=1, gp=shading_Friendly) ##################################### # Model C - C: Column Effect Wong23.C<-gnm(Freq~polviews+fefam+Rscore:fefam,family=poisson, data=Wong23) anova(Wong23.C) mosaic(Wong23.C, formula=~polviews+fefam, main="Column effects model", labeling_args=long.vnames, set_labels=long.lnames, residuals_type="rstandard", labeling=labeling_residuals, suppress=1, gp=shading_Friendly) ##################################### # Model D - R+C: Row and Column Effect oldopt <- options(contrasts = c(factor="contr.treatment", ordered="contr.treatment")) Wong23.RplusC<-gnm(Freq~polviews+fefam+Rscore:Cscore+Cscore:polviews+Rscore:fefam, constrain=c(17,20),constrainTo=c(0,0), family=poisson,tolerance = 1e-12) anova(Wong23.RplusC) mosaic(Wong23.RplusC, formula=~polviews+fefam, main="Column effects model", labeling_args=long.vnames, set_labels=long.lnames, residuals_type="rstandard", labeling=labeling_residuals, suppress=1, gp=shading_Friendly) options(oldopt) ##################################### # Model E - RC: RC(1) model Wong23.RC1<-gnm(Freq~polviews+fefam+Mult(1,polviews,fefam), family=poisson,tolerance = 1e-12) mosaic(Wong23.RC1, formula=~polviews+fefam, main="RC(1) model", labeling_args=long.vnames, set_labels=long.lnames, residuals_type="rstandard", labeling=labeling_residuals, suppress=1, gp=shading_Friendly) ##################################### # LRstats the collection of models models <- list(Indep=Wong23.O, Uniform=Wong23.U, RowEff=Wong23.R, ColEff=Wong23.C, RplusC=Wong23.RplusC, RC1=Wong23.RC1) res <- lapply(models, residuals) boxplot(as.data.frame(res), main="Residuals from various models") aic <- t(as.data.frame(lapply(models, extractAIC))) colnames(aic) <- c("df", "AIC") aic # sort by df aic <- aic[order(aic[,1]),] plot(aic, type = "b", main="AIC plot") text(aic, labels=rownames(aic), pos=c(4,1,3,1,3,1)) ###################################### # compare models; they are not nested, so only some Chisq tests make sense anova(Wong23.O, Wong23.U, Wong23.R, Wong23.C, Wong23.RplusC, Wong23.RC1) anova(Wong23.O, Wong23.U, Wong23.R, Wong23.RplusC, test="Chisq") anova(Wong23.O, Wong23.U, Wong23.C, Wong23.RplusC, test="Chisq")
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/Wong2-3.R
# Wong3-1 Political views, support for women to work and national welfare spending library(vcdExtra) # Data from Wong, R. (2010), Association Models, Los Angeles: Sage, Number 07-164 # Table 3.1, from the General Social Survey, 2006. # Questions: # polviews: Think of self as liberal or conservative # fefam: Better for men to work and women to tend home # natfare: National welfare spending: too little, about right, too much # Table 3.1 Freq<-c( 9, 5, 5, 1, 1, 6, 5, 1, 2, 2, 2, 1, 17,13, 7, 4, 13,22, 9, 1, 7,13, 6, 2, 8,14, 6, 0, 10,29,10, 0, 5,14, 6, 2, 20,38,24, 8, 23,72,34,10, 17,67,36,12, 4,21,12, 4, 7,30, 9, 1, 9,19,14, 2, 2, 9, 8, 3, 1,16,19, 2, 11,28,28,11, 0, 1, 5, 0, 2, 3, 3, 2, 2, 7, 6, 6) polviews<-gl(7,4*3) fefam<-gl(4,1,length=7*4*3) natfare<-gl(3,4,length=7*4*3) long.vnames <- list(set_varnames = c(polviews="Political views", fefam="Females should tend home", natfare="National welfare spending")) long.lnames <- list(polviews = c("Lib++", "2", "3", "Moderate", "5", "6", "Cons++"), fefam = c("Dis+", "Dis", "Agr", "Agr+"), natfare = c("--", "OK", "++") ) ############################################ Wong31 <- data.frame(Freq, polviews, fefam, natfare) Wong31.xtab <- xtabs(Freq ~ polviews+fefam+natfare, data=Wong31) dimnames(Wong31.xtab) <- long.lnames # Quick look at all pairwise associations pairs(Wong31.xtab, gp=shading_Friendly, diag_panel=pairs_diagonal_mosaic) ############################################ # Model 1 - Independence Model Wong31.O<-gnm(Freq~polviews+fefam+natfare,family=poisson, data=Wong31) summary(Wong31.O) mosaic(Wong31.O, main=paste("Independence model",modFit(Wong31.O)), labeling_args=long.vnames, set_labels=long.lnames, split_vertical=c(TRUE, FALSE, FALSE), labeling=labeling_residuals, suppress=2, gp=shading_Friendly) ############################################ # NB: add1 doesn't work with gnm() objects. Re-fit using glm() Wong31.O<-glm(Freq~polviews+fefam+natfare,family=poisson, data=Wong31) # consider all two-way terms add1(Wong31.O, ~.+(polviews + fefam + natfare)^2, test="Chisq") # same result with MASS::addterm addterm(Wong31.O, ~.+(polviews + fefam + natfare)^2, test="Chisq") # or, start with saturated model and drop terms Wong31.sat<-glm(Freq~polviews*fefam*natfare, family=poisson, data=Wong31) drop1(Wong31.sat, test="Chisq") ############################################ # Model 2 - Full Two-way Interaction Wong31.twoway <- update(Wong31.O, ~ .^2) summary(Wong31.twoway) mosaic(Wong31.twoway, main=paste("All two-way model", modFit(Wong31.twoway)), labeling_args=long.vnames, set_labels=long.lnames, split_vertical=c(TRUE, FALSE, FALSE), labeling=labeling_residuals, suppress=1, gp=shading_Friendly) ############################################ # Model 3 - Conditional Independence on polviews Wong31.cond1 <- glm(Freq~polviews * (fefam + natfare), family=poisson) summary(Wong31.cond1) mosaic(Wong31.cond1, main=paste("Cond1: ~P * (F+N)", modFit(Wong31.cond1)), labeling_args=long.vnames, set_labels=long.lnames, split_vertical=c(TRUE, FALSE, FALSE), labeling=labeling_residuals, suppress=1, gp=shading_Friendly) ############################################ # Model 4 - Conditional Independence on fefam Wong31.cond2 <- glm(Freq~polviews*fefam + fefam*natfare,family=poisson) summary(Wong31.cond2) mosaic(Wong31.cond2, main=paste("Cond2: ~F * (P+N)", modFit(Wong31.cond2)), labeling_args=long.vnames, set_labels=long.lnames, split_vertical=c(TRUE, FALSE, FALSE), labeling=labeling_residuals, suppress=1, gp=shading_Friendly) ############################################ # Model 5 - Conditional Independence on natfare Wong31.cond3<-glm(Freq~fefam*natfare+polviews*natfare,family=poisson) summary(Wong31.cond3) mosaic(Wong31.cond3, main=paste("Cond2: ~N * (F+N)", modFit(Wong31.cond3)), labeling_args=long.vnames, set_labels=long.lnames, split_vertical=c(TRUE, FALSE, FALSE), labeling=labeling_residuals, suppress=1, gp=shading_Friendly) anova(Wong31.O, Wong31.cond3, Wong31.cond2, Wong31.cond1,Wong31.twoway, Wong31.sat)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/Wong3-1.R
## housing.R Visualize models from example(housing, package="MASS") # These examples fit a variety of models to the data(housing), giving a 4-way # frequency table of 1681 individuals from the Copenhagen Housing Conditions # Survey, classified by their Type of rental dwelling, perceived Influence on # management of the property, and degree of Contact with other residents. The # response variable here is Satisfaction of householders with their present # housing circumstances. library(vcdExtra) library(MASS) data(housing, package="MASS") oldop <-options(contrasts = c("contr.treatment", "contr.poly")) ########################## # Poisson models for Freq, equivalent to loglinear models ########################## # Baseline model, with Satisfaction as a response house.glm0 <- glm(Freq ~ Infl*Type*Cont + Sat, family = poisson, data = housing) modFit(house.glm0) # labeling_args for mosaic() largs <- list(set_varnames = c( Infl="Influence on management", Cont="Contact among residents", Type="Type of dwelling", Sat="Satisfaction"), abbreviate=c(Type=3)) mosaic(house.glm0, labeling_args=largs, main='Baseline model: [ITC][Sat]') # reorder variables in the mosaic, putting Sat last mosaic(house.glm0, ~ Type+Infl+Cont+Sat, labeling_args=largs, main='Baseline model: [ITC][Sat]') # what terms need to be added? Consider main effects, interactions of Sat with each other MASS::addterm(house.glm0, ~. + Sat:(Infl+Type+Cont), test = "Chisq") # add all two way terms with Satisfaction house.glm1 <- update(house.glm0, . ~ . + Sat*(Infl+Type+Cont)) # did it get better? anova(house.glm0, house.glm1, test="Chisq") # plot it mosaic(house.glm1, labeling_args=largs, main='Model [IS][TS][CS]', gp=shading_Friendly) # Same model, fit by iterative proportional scaling (house.loglm <- MASS::loglm(Freq ~ Infl*Type*Cont + Sat*(Infl+Type+Cont), data = housing)) # Can we drop any terms? MASS::dropterm(house.glm1, test = "Chisq") # Need to add any terms? MASS::addterm(house.glm1, ~. + Sat:(Infl+Type+Cont)^2, test = "Chisq") # add an interaction house.glm2 <- update(house.glm1, . ~ . + Sat:Infl:Type) LRstats(house.glm0, house.glm1, house.glm2) ########################## # Effect plots, for glm1 model ########################## library(effects) house.eff <-allEffects(house.glm1) # show the interactions of Infl, Cont and Type with Sat plot(house.eff, 'Infl:Sat', x.var='Sat', xlab="Satisfaction") plot(house.eff, 'Infl:Sat', x.var='Infl', xlab="Influence") # same plot in one panel, no std errors shown plot(house.eff, 'Infl:Sat', x.var='Sat', xlab="Satisfaction", multiline=TRUE) plot(house.eff, 'Cont:Sat', x.var='Sat', xlab="Satisfaction") plot(house.eff, 'Type:Sat', x.var='Sat', xlab="Satisfaction") ########################## # multinomial model ########################## library(nnet) # multinomial model, similar in spirit to house.glm1 (house.mult<- multinom(Sat ~ Infl + Type + Cont, weights = Freq, data = housing)) # Do we need a more complex model? house.mult2 <- multinom(Sat ~ Infl*Type*Cont, weights = Freq, data = housing) anova(house.mult, house.mult2) # effect plots for multinomial model house.effm <- allEffects(house.mult) plot(house.effm, 'Infl', xlab='Influence on management', style="stacked", main="Multinomial: Infl effect plot") plot(house.effm, 'Cont', xlab='Contact among residents', style="stacked", main="Multinomial: Cont effect plot") plot(house.effm, 'Type', xlab='Type of dwelling', style="stacked", main="Multinomial: Type effect plot") ########################## # proportional odds model ########################## (house.plr <- polr(Sat ~ Infl + Type + Cont, data = housing, weights = Freq)) # Test proportional odds assumption by likelihood ratio test # NB: multinom() objects do not have a df.residual component, so we have # to use the difference in edf to get df for the test pchisq(deviance(house.plr) - deviance(house.mult), df = house.mult$edf -house.plr$edf, lower.tail = FALSE) # try more complex models house.plr2 <- stepAIC(house.plr, ~.^2) house.plr2$anova house.effp <- allEffects(house.plr) plot(house.effp, 'Infl', xlab='Influence on management', style="stacked", main="Proportional odds: Infl effect plot") plot(house.effp, 'Cont', xlab='Contact among residents', style="stacked", main="Proportional odds: Cont effect plot") plot(house.effp, 'Type', xlab='Type of dwelling', style="stacked", main="Proportional odds: Type effect plot") options(oldop)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/housing.R
## Mental health data: mosaics for glm() and gnm() models library(gnm) library(vcdExtra) data(Mental) # display the frequency table (Mental.tab <- xtabs(Freq ~ mental+ses, data=Mental)) # fit independence model # Residual deviance: 47.418 on 15 degrees of freedom indep <- glm(Freq ~ mental+ses, family = poisson, data = Mental) deviance(indep) long.labels <- list(set_varnames = c(mental="Mental Health Status", ses="Parent SES")) mosaic(indep,residuals_type="rstandard", labeling_args = long.labels, labeling=labeling_residuals, main="Mental health data: Independence") # as a sieve diagram mosaic(indep, labeling_args = long.labels, panel=sieve, gp=shading_Friendly, main="Mental health data: Independence") # fit linear x linear (uniform) association. Use integer scores for rows/cols Cscore <- as.numeric(Mental$ses) Rscore <- as.numeric(Mental$mental) # column effects model (ses) coleff <- glm(Freq ~ mental + ses + Rscore:ses, family = poisson, data = Mental) mosaic(coleff,residuals_type="rstandard", labeling_args = long.labels, labeling=labeling_residuals, suppress=1, gp=shading_Friendly, main="Mental health data: Col effects (ses)") # row effects model (mental) roweff <- glm(Freq ~ mental + ses + mental:Cscore, family = poisson, data = Mental) mosaic(roweff,residuals_type="rstandard", labeling_args = long.labels, labeling=labeling_residuals, suppress=1, gp=shading_Friendly, main="Mental health data: Row effects (mental)") linlin <- glm(Freq ~ mental + ses + Rscore:Cscore, family = poisson, data = Mental) # compare models anova(indep, roweff, coleff, linlin) AIC(indep, roweff, coleff, linlin) mosaic(linlin,residuals_type="rstandard", labeling_args = long.labels, labeling=labeling_residuals, suppress=1, gp=shading_Friendly, main="Mental health data: Linear x Linear") ## Goodman Row-Column association model fits well (deviance 3.57, df 8) Mental$mental <- C(Mental$mental, treatment) Mental$ses <- C(Mental$ses, treatment) RC1model <- gnm(Freq ~ mental + ses + Mult(mental, ses), family = poisson, data = Mental) mosaic(RC1model,residuals_type="rstandard", labeling_args = long.labels, labeling=labeling_residuals, suppress=1, gp=shading_Friendly, main="Mental health data: RC1 model")
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/mental-glm.R
### mosaic3d-demo: proof-of-concept for exploring 3D mosaic plots ## ## split a 3D object along a given dimension, dim, into copies whose ## extent along that dimension are given by the proportions in vector p ## (rescaled to proportions if they are not already so). ## ## The objects are slightly separated along that dimension, allowing ## a total inter-object space = space ## split3d <- function(obj, p, dim, space=.10) { range <-range3d(obj) min <- range[1,] p <- p/sum(p) # assure proportions uspace <- space/(length(p)-1) # unit space between objects scales <- p * (1-space) shifts <- c(0, cumsum(p)[-length(p)])*diff(range[,dim]) result <- list() for (i in seq_along(p)) { xscale <- yscale <- zscale <- 1 xshift <- yshift <- zshift <- 0 if (dim == 1) { xscale <- scales[i] xshift <- shifts[i] + min[1]*(1-xscale) + (uspace * (i-1)) } else if (dim == 2) { yscale <- scales[i] yshift <- shifts[i] + min[2]*(1-yscale) + (uspace * (i-1)) } else if (dim == 3) { zscale <- scales[i] zshift <- shifts[i] + min[3]*(1-zscale) + (uspace * (i-1)) } result[[i]] <- translate3d(scale3d(obj, xscale, yscale, zscale), xshift, yshift, zshift) } result } range3d <- function(obj) { if (!"vb" %in% names(obj)) stop("Not a mesh3d or shape3d object") x <- with(obj, range(vb[1,]/vb[4,])) y <- with(obj, range(vb[2,]/vb[4,])) z <- with(obj, range(vb[3,]/vb[4,])) result <- cbind(x,y,z) rownames(result)<- c('min', 'max') result } label3d <- function(objlist, dim, text, offset=.1, adj=c(0.5, 1), ...) { ranges <- lapply(objlist, range3d) loc <- t(sapply(ranges, colMeans)) # positions of labels on dimension dim min <- t(sapply(ranges, function(x) x[1,])) # other dimensions at min values xyz <- min - offset xyz[,dim] <- loc[,dim] texts3d(xyz, texts=text, adj=adj, ...) } library(rgl) # level 1 open3d() # use transparent colors for the side walls of mosaic cubes crgb <- col2rgb(c("red", "gray90", "blue"))/255 clr <-rbind(crgb, alpha=0.5) col <- rgb(clr[1,], clr[2,], clr[3,], clr[4,]) #col <- c("#FF000080", "#E5E5E580", "#0000FF80") sl0 <- cube <- cube3d(alpha=0.3) sl1 <- split3d(sl0, c(.2, .3, .5), 1) shapelist3d(sl1, col=col) label3d(sl1, 1, c("A1", "A2", "A3")) # level 2 open3d() sl2 <- list() for (i in seq_along(sl1)) { p <- runif(1, .2, .8) sl2 <- c(sl2, split3d(sl1[[i]], c(p, 1-p), 2, space=.1)) } shapelist3d(sl2, col=col) label3d(sl1, 1, c("A1", "A2", "A3")) label3d(sl2[1:2], 2, c("B1", "B2")) # level 3 open3d() sl3 <- list() for (i in seq_along(sl2)) { p <- runif(1, .2, .8) sl3 <- c(sl3, split3d(sl2[[i]], c(p, 1-p), 3, space=.05)) } shapelist3d(sl3, col=col) label3d(sl1, 1, c("A1", "A2", "A3")) label3d(sl2[1:2], 2, c("B1", "B2")) #label3d(sl3[1:2], 3, c("C1", "C2")) label3d(sl3[1:2], 3, c("C1", "C2"), adj=rev(c(0.5, 1)))
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/mosaic3d-demo.R
## mosaic3d-hec 2D and 3D visualizations of HairEyeColor data library(vcdExtra) # two-way mosaic displays HairEye <- margin.table(HairEyeColor, c(1,2)) HairEye mosaic(HairEye, shade=TRUE) # three-way mosaic displays structable(HairEyeColor) # mutual independence model mosaic(HairEyeColor, shade=TRUE) # joint independence of Hair*Eye with Sex mosaic(HairEyeColor, expected =~(Hair*Eye)+Sex) # observed frequencies, mutual independence mosaic3d(HairEyeColor) # expected frequencies under mutual independence mosaic3d(HairEyeColor, type="expected") # expected frequencies under joint independence mosaic3d(HairEyeColor, type="expected", expected =~(Hair*Eye)+Sex)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/mosaic3d-hec.R
# Occupational status data from Goodman (1979) and Duncan (1979) # Fit a variety of models. Compare mosaic using expected= to mosaic.glm # Occ status (1:8)-- professional, managerial, upper non-man, lower non-man, # ... unskilled library(gnm) library(vcdExtra) data(occupationalStatus, package="datasets") str(occupationalStatus) occupationalStatus # graphics::mosaicplot is the default plot method for a table plot(occupationalStatus, shade=TRUE) # define long labels for use in mosaics long.labels <- list(set_varnames = c(origin="origin: Son's status", destination="destination: Father's status")) mosaic(occupationalStatus, shade=TRUE, main="Occupational status: Independence model", labeling_args = long.labels, legend=FALSE) # the standard model of independence indep <- glm(Freq ~ origin + destination, family = poisson, data=occupationalStatus) # the same mosaic, using the fitted model mosaic(indep, main="Independence model", labeling_args = long.labels, legend=FALSE, gp=shading_Friendly) # fit the model of quasi-independence, ignoring the diagonal cells quasi <- gnm(Freq ~ origin + destination + Diag(origin,destination), family=poisson, data=occupationalStatus) #str(quasi$data) anova(quasi, test="Chisq") ## BUGLET (vcd): the diagonal cells should be considered 0 here--- outlined in black mosaic(occupationalStatus, expected=fitted(quasi), main="Quasi-independence model", labeling_args = long.labels, legend=FALSE, gp=shading_Friendly) ## using mosaic.gnm mosaic(quasi, main="Quasi-independence model", labeling_args = long.labels, legend=FALSE, gp=shading_Friendly, labeling=labeling_residuals) # symmetry model symmetry <- glm(Freq ~ Symm(origin, destination), family=poisson, data=occupationalStatus) # mosaic(occupationalStatus, expected=fitted(symmetry), main="Symmetry model", # gp=shading_Friendly, labeling=labeling_residuals, labeling_args = long.labels ) # using mosaic.glm --- OK mosaic(symmetry, main="Symmetry model", gp=shading_Friendly, labeling=labeling_residuals, labeling_args = long.labels ) quasi.symm <- glm(Freq ~ origin + destination + Symm(origin, destination), family=poisson, data=occupationalStatus) anova(quasi.symm) mosaic(occupationalStatus, expected=fitted(quasi.symm), main="Quasi-symmetry model") # model comparisons anova(independence, quasi, quasi.symm, test="Chisq") # compare symmetry to quasi summetry anova(symmetry, quasi.symm, test="Chisq") # association models # uniform association, aka linear x linear association Rscore <- as.vector(row(occupationalStatus)) Cscore <- as.vector(col(occupationalStatus)) uniform <- gnm(Freq ~ origin + destination + Rscore:Cscore, family=poisson, data=occupationalStatus) mosaic(uniform, main="Uniform association model", labeling_args = long.labels, legend=FALSE, gp=shading_Friendly, labeling=labeling_residuals ) RChomog <- gnm(Freq ~ origin + destination + Diag(origin, destination) + MultHomog(origin, destination), family=poisson, data=occupationalStatus) mosaic(RChomog, main="RC homogeneous model", labeling_args = long.labels, legend=FALSE, gp=shading_Friendly, labeling=labeling_residuals) # RC1 - heterogeneous association RC1 <- gnm(Freq ~ origin + destination + Diag(origin, destination) + Mult(origin, destination), family=poisson, data=occupationalStatus) mosaic(RC1, main="RC heterogeneous model", labeling_args = long.labels, legend=FALSE, gp=shading_Friendly, labeling=labeling_residuals)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/occStatus.R
# UCBAdmissions data: Conditional independence via loglm and glm library(vcd) data("UCBAdmissions") structable(Dept ~ Admit+Gender,UCBAdmissions) ## conditional independence in UCB admissions data mod.1 <- loglm(~ Dept * (Gender + Admit), data=UCBAdmissions) mod.1 # this is correct, except the Pearson residuals dont show that # all the lack of fit is concentrated in Dept A mosaic(mod.1, gp=shading_Friendly, labeling=labeling_residuals) library(vcdExtra) # using glm() berkeley <- as.data.frame(UCBAdmissions) mod.3 <- glm(Freq ~ Dept * (Gender+Admit), data=berkeley, family="poisson") summary(mod.3) # (BUG FIXED )the large residuals are all in Dept A mosaic(mod.3, residuals_type="rstandard", labeling=labeling_residuals)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/ucb-glm.R
# VisualAcuity data: Quasi- and Symmetry models library(vcdExtra) library(gnm) women <- subset(VisualAcuity, gender=="female", select=-gender) indep <- glm(Freq ~ right + left, data = women, family=poisson) mosaic(indep, residuals_type="rstandard", gp=shading_Friendly, main="Vision data: Independence (women)" ) quasi.indep <- glm(Freq ~ right + left + Diag(right, left), data = women, family = poisson) mosaic(quasi.indep, residuals_type="rstandard", gp=shading_Friendly, main="Quasi-Independence (women)" ) symmetry <- glm(Freq ~ Symm(right, left), data = women, family = poisson) # BUG FIXED mosaic(symmetry, residuals_type="rstandard", gp=shading_Friendly, main="Symmetry model (women)") quasi.symm <- glm(Freq ~ right + left + Symm(right, left), data = women, family = poisson) mosaic(quasi.symm, residuals_type="rstandard", gp=shading_Friendly, main="Quasi-Symmetry model (women)") # model comparisons: for *nested* models anova(indep, quasi.indep, quasi.symm, test="Chisq") anova(symmetry, quasi.symm, test="Chisq") # model summaries, with AIC and BIC models <- glmlist(indep, quasi.indep, symmetry, quasi.symm) LRstats(models)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/vision-quasi.R
# Yaish data: Unidiff model for 3-way table library(gnm) library(vcd) data(yaish) # Ignore orig==7 & dest == 7 with very few cases yaish <- yaish[,1:6,1:6] ## Fit mutual independence model. long.labels <- list(set_varnames = c(orig="Origin status", dest="Destination status", educ="Education")) mosaic(~orig + dest + educ, data=yaish, gp=shading_Friendly, labeling_args=long.labels) ## Fit conditional independence model mosaic(~orig + dest | educ, data=yaish, gp=shading_Friendly, labeling_args=long.labels) ## Fit the "UNIDIFF" mobility model across education levels ## unidiff <- gnm(Freq ~ educ*orig + educ*dest + Mult(Exp(educ), orig:dest), family = poisson, data = yaish, subset = (dest != 7 & orig != 7)) structable(round(residuals(unidiff), digits=2)) # can use mosaic.loglm, passing residuals mosaic(yaish[, 1:6, 1:6], residuals=residuals(unidiff), gp=shading_Friendly, labeling_args=long.labels) # what about mosaic.gnm? mosaic(unidiff, gp=shading_Friendly, labeling_args=long.labels)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/yaish-unidiff.R
## Models for Yamaguchi (1987) data on social mobility in US, UK and Japan, following Xie (1992) ## These models reproduce the results in Table 1, appplied to the off-diagonal cells library(gnm) library(vcdExtra) data(Yamaguchi87) # create table form Yama.tab <- xtabs(Freq ~ Father + Son + Country, data=Yamaguchi87) # define labeling_args for convenient reuse in 3-way displays largs <- list(rot_labels=c(right=0), offset_varnames = c(right = 0.6), offset_labels = c(right = 0.2), set_varnames = c(Father="Father's status", Son="Son's status") ) # no association between F and S given country ('perfect mobility') # asserts same associations for all countries yamaNull <- gnm(Freq ~ (Father + Son) * Country, data=Yamaguchi87, family=poisson) LRstats(yamaNull) mosaic(yamaNull, ~Country + Son + Father, condvars="Country", labeling_args=largs, main="[FC][SC] Null [FS] association (perfect mobility)") ## same, with data in xtabs form #yamaNull <- gnm(Freq ~ (Father + Son) * Country, data=Yama.tab, family=poisson) #LRstats(yamaNull) #mosaic(yamaNull, ~Country + Son + Father, condvars="Country", # labeling_args=largs, # main="[FC][SC] Null [FS] association (perfect mobility)") # ignore diagonal cells, overall #yamaDiag0 <- gnm(Freq ~ (Father + Son) * Country + Diag(Father, Son), data=Yama.tab, family=poisson) #LRstats(yamaDiag0) # same, using update() yamaDiag0 <- update(yamaNull, ~ . + Diag(Father, Son)) LRstats(yamaDiag0) # ignore diagonal cells in each Country [Model NA in Xie(1992), Table 1] yamaDiag <- update(yamaNull, ~ . + Diag(Father, Son):Country) LRstats(yamaDiag) mosaic(yamaDiag, ~Country + Son + Father, condvars="Country", labeling_args=largs, gp=shading_Friendly, main="[FC][SC] Quasi perfect mobility, +Diag(F,S)") # fit models using integer scores for rows/cols Rscore <- as.numeric(Yamaguchi87$Father) Cscore <- as.numeric(Yamaguchi87$Son) # cross-nationally homogeneous row effect associations (Xie, model R_o) yamaRo <- update(yamaDiag, ~ . + Father:Cscore) LRstats(yamaRo) mosaic(yamaRo, ~Country + Son + Father, condvars="Country", labeling_args=largs, gp=shading_Friendly, main="Model Ro: homogeneous row effects, +Father:j ") # cross-nationally log multiplicative row effect associations (Xie, model R_x) yamaRx <- update(yamaDiag, ~ . + Mult(Father:Cscore, Exp(Country))) LRstats(yamaRx) # cross-nationally homogeneous col effect associations (Xie, model C_o) yamaCo <- update(yamaDiag, ~ . + Rscore:Son) LRstats(yamaCo) mosaic(yamaCo, ~Country + Son + Father, condvars="Country", labeling_args=largs, gp=shading_Friendly, main="Model Co: homogeneous col effects, +i:Son") # cross-nationally log multiplicative col effect associations (Xie, model C_x) yamaCx <- update(yamaDiag, ~ . + Mult(Rscore:Son, Exp(Country))) LRstats(yamaCx) # cross-nationally homogeneous row + col effect associations I (Xie, model (R+C)_o) yamaRpCo <- update(yamaDiag, ~ . + Father:Cscore + Rscore:Son) LRstats(yamaRpCo) mosaic(yamaRpCo, ~Country + Son + Father, condvars="Country", labeling_args=largs, gp=shading_Friendly, main="Model (R+C)o: homogeneous, F:j + i:S") # cross-nationally log multiplicative row + col effect associations I (Xie, model (R+C)_x) yamaRpCx <- update(yamaDiag, ~ . + Mult(Father:Cscore + Rscore:Son, Exp(Country))) LRstats(yamaRpCx) mosaic(yamaRpCx, ~Country + Son + Father, condvars="Country", labeling_args=largs, gp=shading_Friendly, main="Model (R+C)x: log multiplicative (Fj + iS) : Country") # cross-nationally homogeneous row and col effect associations II (Xie, model RC_o) yamaRCo <- update(yamaDiag, ~ . + Mult(Father,Son)) LRstats(yamaRCo) mosaic(yamaRCo, ~Country + Son + Father, condvars="Country", labeling_args=largs, gp=shading_Friendly, main="Model RCo: homogeneous RC(1)") # cross-nationally log multiplicative row and col effect associations II (Xie, model RC_x) yamaRCx <- update(yamaDiag, ~ . + Mult(Father,Son, Exp(Country))) LRstats(yamaRCx) mosaic(yamaRCx, ~Country + Son + Father, condvars="Country", labeling_args=largs, gp=shading_Friendly, main="Model RCx: log multiplicative RC(1) : Country") # cross-nationally homogeneous full two-way RxC association (Xie, model FI_o) yamaFIo <- update(yamaDiag, ~ . + Father:Son) LRstats(yamaFIo) # cross-nationally log multiplicative full two-way RxC association (Xie, model FI_x) yamaFIx <- update(yamaDiag, ~ . + Mult(Father:Son, Exp(Country))) LRstats(yamaFIx) # compare models models <- glmlist(yamaNull, yamaDiag, yamaRo, yamaRx, yamaCo, yamaCx, yamaRpCo, yamaRpCx, yamaRCo, yamaRCx, yamaFIo, yamaFIx) LRstats(models) # extract models sumaries, consider as factorial of RC model by layer model BIC <- matrix(LRstats(models)$BIC[-(1:2)], 5, 2, byrow=TRUE) dimnames(BIC) <- list("Father-Son model" = c("row eff", "col eff", "row+col", "RC(1)", "R:C"), "Country model" = c("homogeneous", "log multiplicative")) BIC matplot(BIC, type='b', xlab="Father-Son model", xaxt='n', pch=15:16, cex=1.5, cex.lab=1.5, main="Yamaguchi-Xie models: R:C model by Layer model Summary") axis(side=1, at=1:nrow(BIC), labels=rownames(BIC), cex.axis=1.2) text(5, BIC[5,], colnames(BIC), pos=2, col=1:2, cex=1.2) text(5, max(BIC[5,])+10, "Country model", pos=2, cex=1.3) AIC <- matrix(LRstats(models)$AIC[-(1:2)], 5, 2, byrow=TRUE) dimnames(AIC) <- list("Father-Son model" = c("row eff", "col eff", "row+col", "RC(1)", "R:C"), "Country model" = c("homogeneous", "log multiplicative")) AIC matplot(AIC, type='b', xlab="Father-Son model", xaxt='n', pch=15:16, cex=1.5, cex.lab=1.5, main="Yamaguchi-Xie models: R:C model by Layer model Summary") axis(side=1, at=1:nrow(AIC), labels=rownames(AIC), cex.axis=1.2) text(5, AIC[5,], colnames(AIC), pos=2, col=1:2, cex=1.2) text(5, max(AIC[5,])+10, "Country model", pos=2, cex=1.3)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/demo/yamaguchi-xie.R
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut05-", fig.align = "center", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Old Sweave options # \SweaveOpts{engine=R,eps=TRUE,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{engine=R,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{prefix.string=fig/vcd-tut,eps=FALSE} # \SweaveOpts{keep.source=TRUE} # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ## ---- spine1------------------------------------------------------------------ (spine(Improved ~ Age, data = Arthritis, breaks = 3)) (spine(Improved ~ Age, data = Arthritis, breaks = "Scott")) ## ----------------------------------------------------------------------------- cdplot(Improved ~ Age, data = Arthritis) ## ----------------------------------------------------------------------------- cdplot(Improved ~ Age, data = Arthritis) with(Arthritis, rug(jitter(Age), col="white", quiet=TRUE)) ## ---- donner1----------------------------------------------------------------- data(Donner, package="vcdExtra") str(Donner) ## ---- donner2a, fig=FALSE, eval=FALSE----------------------------------------- # # separate linear fits on age for M/F # ggplot(Donner, aes(age, survived, color = sex)) + # geom_point(position = position_jitter(height = 0.02, width = 0)) + # stat_smooth(method = "glm", # method.args = list(family = binomial), # formula = y ~ x, # alpha = 0.2, size=2, aes(fill = sex)) ## ---- donner2b, fig=FALSE, eval=FALSE----------------------------------------- # # separate quadratics # ggplot(Donner, aes(age, survived, color = sex)) + # geom_point(position = position_jitter(height = 0.02, width = 0)) + # stat_smooth(method = "glm", # method.args = list(family = binomial), # formula = y ~ poly(x,2), # alpha = 0.2, size=2, aes(fill = sex)) ## ----------------------------------------------------------------------------- # separate linear fits on age for M/F ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ x, alpha = 0.2, size=2, aes(fill = sex)) # separate quadratics ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ poly(x,2), alpha = 0.2, size=2, aes(fill = sex))
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/continuous.R
--- title: "Continuous predictors" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Continuous predictors} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut05-", fig.align = "center", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Old Sweave options # \SweaveOpts{engine=R,eps=TRUE,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{engine=R,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{prefix.string=fig/vcd-tut,eps=FALSE} # \SweaveOpts{keep.source=TRUE} # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ``` When continuous predictors are available---and potentially important---in explaining a categorical outcome, models for that outcome include: logistic regression (binary response), the proportional odds model (ordered polytomous response), multinomial (generalized) logistic regression. Many of these are special cases of the generalized linear model using the `"poisson"` or `"binomial"` family and their relatives. ## Spine and conditional density plots {#sec:spine} I don't go into fitting such models here, but I would be remiss not to illustrate some visualizations in `vcd` that are helpful here. The first of these is the spine plot or spinogram [@vcd:Hummel:1996], produced with `spine()`. These are special cases of mosaic plots with specific spacing and shading to show how a categorical response varies with a continuous or categorical predictor. They are also a generalization of stacked bar plots where not the heights but the *widths* of the bars corresponds to the relative frequencies of `x`. The heights of the bars then correspond to the conditional relative frequencies of `y` in every `x` group. ***Example***: For the `Arthritis` data, we can see how `Improved` varies with `Age` as follows. `spine()` takes a formula of the form `y ~ x` with a single dependent factor and a single explanatory variable `x` (a numeric variable or a factor). The range of a numeric variable`x` is divided into intervals based on the `breaks` argument, and stacked bars are drawn to show the distribution of `y` as `x` varies. As shown below, the discrete table that is visualized is returned by the function. ```{r, spine1} #| spine1, #| fig.height = 6, #| fig.width = 6, #| fig.show = "hold", #| out.width = "46%", #| fig.align = "center", #| cap = "Spine plots for the `Arthritis` data" (spine(Improved ~ Age, data = Arthritis, breaks = 3)) (spine(Improved ~ Age, data = Arthritis, breaks = "Scott")) ``` The conditional density plot [@vcd:Hofmann+Theus] is a further generalization. This visualization technique is similar to spinograms, but uses a smoothing approach rather than discretizing the explanatory variable. As well, it uses the original `x` axis and not a distorted one. ```{r} #| cdplot, #| fig.height = 5, #| fig.width = 5, #| cap = "Conditional density plot for the `Arthritis` data showing the variation of Improved with Age." cdplot(Improved ~ Age, data = Arthritis) ``` In such plots, it is useful to also see the distribution of the observations across the horizontal axis, e.g., with a `rug()` plot. \@ref{fig:cd-plot} uses `cdplot()` from the `graphics` package rather than `cd_plot()` from `vcd`, and is produced with ```{r} #| cdplot1, #| fig.height = 5, #| fig.width = 5, cdplot(Improved ~ Age, data = Arthritis) with(Arthritis, rug(jitter(Age), col="white", quiet=TRUE)) ``` From this figure it can be easily seen that the proportion of patients reporting Some or Marked improvement increases with Age, but there are some peculiar bumps in the distribution. These may be real or artifactual, but they would be hard to see with most other visualization methods. When we switch from non-parametric data exploration to parametric statistical models, such effects are easily missed. ## Model-based plots: effect plots and `ggplot2 plots` {#sec:modelplots} The nonparametric conditional density plot uses smoothing methods to convey the distributions of the response variable, but displays that are simpler to interpret can often be obtained by plotting the predicted response from a parametric model. For complex `glm()` models with interaction effects, the `effects` package provides the most useful displays, plotting the predicted values for a given term, averaging over other predictors not included in that term. I don't illustrate this here, but see @effects:1,@effects:2 and `help(package="effects")`. Here I just briefly illustrate the capabilities of the `ggplot2` package for model-smoothed plots of categorical responses in `glm()` models. ***Example***: The `Donner` data frame in `vcdExtra` gives details on the survival of 90 members of the Donner party, a group of people who attempted to migrate to California in 1846. They were trapped by an early blizzard on the eastern side of the Sierra Nevada mountains, and before they could be rescued, nearly half of the party had died. What factors affected who lived and who died? ```{r, donner1} data(Donner, package="vcdExtra") str(Donner) ``` A potential model of interest is the logistic regression model for $Pr(survived)$, allowing separate fits for males and females as a function of `age`. The key to this is the `stat_smooth()` function, using `method = "glm", method.args = list(family = binomial)`. The `formula = y ~ x` specifies a linear fit on the logit scale (\@ref{fig:donner3}, left) ```{r, donner2a, fig=FALSE, eval=FALSE} # separate linear fits on age for M/F ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ x, alpha = 0.2, size=2, aes(fill = sex)) ``` Alternatively, we can allow a quadratic relation with `age` by specifying `formula = y ~ poly(x,2)` (@ref(fig:donner3), right). ```{r, donner2b, fig=FALSE, eval=FALSE} # separate quadratics ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ poly(x,2), alpha = 0.2, size=2, aes(fill = sex)) ``` ```{r} #| donner3a, #| echo = FALSE, #| fig.height = 6, #| fig.width = 6, #| fig.show = "hold", #| out.width = "46%", #| cap = "Logistic regression plots for the `Donner` data showing survival vs. age, by sex. Left: linear logistic model; right: quadratic model {#fig:donner3}" # separate linear fits on age for M/F ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ x, alpha = 0.2, size=2, aes(fill = sex)) # separate quadratics ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ poly(x,2), alpha = 0.2, size=2, aes(fill = sex)) ``` These plots very nicely show (a) the fitted $Pr(survived)$ for males and females; (b) confidence bands around the smoothed model fits and (c) the individual observations by jittered points at 0 and 1 for those who died and survived, respectively. # References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/continuous.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut01-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Old Sweave options # \SweaveOpts{engine=R,eps=TRUE,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{engine=R,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{prefix.string=fig/vcd-tut,eps=FALSE} # \SweaveOpts{keep.source=TRUE} # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ## ---- case-form--------------------------------------------------------------- names(Arthritis) # show the variables str(Arthritis) # show the structure head(Arthritis,5) # first 5 observations, same as Arthritis[1:5,] ## ---- frequency-form---------------------------------------------------------- # Agresti (2002), table 3.11, p. 106 GSS <- data.frame( expand.grid(sex = c("female", "male"), party = c("dem", "indep", "rep")), count = c(279,165,73,47,225,191)) GSS names(GSS) str(GSS) sum(GSS$count) ## ---- table-form1------------------------------------------------------------- str(HairEyeColor) # show the structure sum(HairEyeColor) # number of cases sapply(dimnames(HairEyeColor), length) # table dimension sizes ## ---- table-form2------------------------------------------------------------- # A 4 x 4 table Agresti (2002, Table 2.8, p. 57) Job Satisfaction JobSat <- matrix(c( 1, 2, 1, 0, 3, 3, 6, 1, 10,10,14, 9, 6, 7,12,11), 4, 4) dimnames(JobSat) = list( income = c("< 15k", "15-25k", "25-40k", "> 40k"), satisfaction = c("VeryD", "LittleD", "ModerateS", "VeryS") ) JobSat ## ---- table-form3------------------------------------------------------------- JobSat <- as.table(JobSat) str(JobSat) ## ---- relevel, eval=FALSE----------------------------------------------------- # dimnames(JobSat)$income <- c(7.5,20,32.5,60) # dimnames(JobSat)$satisfaction <- 1:4 ## ---- reorder1---------------------------------------------------------------- HairEyeColor <- HairEyeColor[, c(1,3,4,2), ] str(HairEyeColor) ## ---- reorder2, echo=TRUE, eval=FALSE----------------------------------------- # Arthritis <- read.csv("arthritis.txt",header=TRUE) # Arthritis$Improved <- ordered(Arthritis$Improved, # levels=c("None", "Some", "Marked") # ) ## ----------------------------------------------------------------------------- data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) mosaic(art, gp = shading_max, split_vertical = TRUE, main="Arthritis: [Treatment] [Improved]") ## ---- reorder3---------------------------------------------------------------- UCB <- aperm(UCBAdmissions, c(2, 1, 3)) dimnames(UCB)[[2]] <- c("Yes", "No") names(dimnames(UCB)) <- c("Sex", "Admit?", "Department") # display as a flattened table stats::ftable(UCB) ## ---- structable-------------------------------------------------------------- structable(HairEyeColor) # show the table: default structable(Hair+Sex ~ Eye, HairEyeColor) # specify col ~ row variables ## ---- structable1,eval=FALSE-------------------------------------------------- # HSE < - structable(Hair+Sex ~ Eye, HairEyeColor) # save structable object # mosaic(HSE) # plot it ## ---- table-setup------------------------------------------------------------- n=500 A <- factor(sample(c("a1","a2"), n, rep=TRUE)) B <- factor(sample(c("b1","b2"), n, rep=TRUE)) C <- factor(sample(c("c1","c2"), n, rep=TRUE)) mydata <- data.frame(A,B,C) ## ---- table-ex1--------------------------------------------------------------- # 2-Way Frequency Table attach(mydata) mytable <- table(A,B) # A will be rows, B will be columns mytable # print table margin.table(mytable, 1) # A frequencies (summed over B) margin.table(mytable, 2) # B frequencies (summed over A) prop.table(mytable) # cell percentages prop.table(mytable, 1) # row percentages prop.table(mytable, 2) # column percentages ## ---- table-ex2--------------------------------------------------------------- # 3-Way Frequency Table mytable <- table(A, B, C) ftable(mytable) ## ---- xtabs-ex1--------------------------------------------------------------- # 3-Way Frequency Table mytable <- xtabs(~A+B+C, data=mydata) ftable(mytable) # print table summary(mytable) # chi-square test of indepedence ## ---- xtabs-ex2--------------------------------------------------------------- (GSStab <- xtabs(count ~ sex + party, data=GSS)) summary(GSStab) ## ---- dayton1----------------------------------------------------------------- data("DaytonSurvey", package="vcdExtra") str(DaytonSurvey) head(DaytonSurvey) ## ---- dayton2----------------------------------------------------------------- # data in frequency form # collapse over sex and race Dayton.ACM.df <- aggregate(Freq ~ cigarette+alcohol+marijuana, data=DaytonSurvey, FUN=sum) Dayton.ACM.df ## ---- dayton3----------------------------------------------------------------- # in table form Dayton.tab <- xtabs(Freq ~ cigarette+alcohol+marijuana+sex+race, data=DaytonSurvey) structable(cigarette+alcohol+marijuana ~ sex+race, data=Dayton.tab) ## ---- dayton4----------------------------------------------------------------- # collapse over sex and race Dayton.ACM.tab <- apply(Dayton.tab, MARGIN=1:3, FUN=sum) Dayton.ACM.tab <- margin.table(Dayton.tab, 1:3) # same result structable(cigarette+alcohol ~ marijuana, data=Dayton.ACM.tab) ## ---- dayton5----------------------------------------------------------------- library(plyr) Dayton.ACM.df <- plyr::ddply(DaytonSurvey, .(cigarette, alcohol, marijuana), plyr::summarise, Freq=sum(Freq)) Dayton.ACM.df ## ---- collapse1--------------------------------------------------------------- # create some sample data in frequency form sex <- c("Male", "Female") age <- c("10-19", "20-29", "30-39", "40-49", "50-59", "60-69") education <- c("low", 'med', 'high') data <- expand.grid(sex=sex, age=age, education=education) counts <- rpois(36, 100) # random Possion cell frequencies data <- cbind(data, counts) # make it into a 3-way table t1 <- xtabs(counts ~ sex + age + education, data=data) structable(t1) ## ---- collapse2--------------------------------------------------------------- # collapse age to 3 levels, education to 2 levels t2 <- collapse.table(t1, age=c("10-29", "10-29", "30-49", "30-49", "50-69", "50-69"), education=c("<high", "<high", "high")) structable(t2) ## ----titanicp1---------------------------------------------------------------- table(Titanicp$sibsp, Titanicp$parch) ## ----titanicp2---------------------------------------------------------------- library(dplyr) Titanicp <- Titanicp |> mutate(sibspF = case_match(sibsp, 0 ~ "0", 1 ~ "1", 2:max(sibsp) ~ "2+")) |> mutate(sibspF = ordered(sibspF)) |> mutate(parchF = case_match(parch, 0 ~ "0", 1 ~ "1", 2:max(parch) ~ "2+")) |> mutate(parchF = ordered(parchF)) table(Titanicp$sibspF, Titanicp$parchF) ## ---- convert-ex1------------------------------------------------------------- as.data.frame(GSStab) ## ---- convert-ex2------------------------------------------------------------- Art.tab <- with(Arthritis, table(Treatment, Sex, Improved)) str(Art.tab) ftable(Art.tab) ## ---- convert-ex3------------------------------------------------------------- Art.df <- expand.dft(Art.tab) str(Art.df) ## ---- tv1--------------------------------------------------------------------- tv.data<-read.table(system.file("extdata","tv.dat", package="vcdExtra")) head(tv.data,5) ## ---- tv2,eval=FALSE---------------------------------------------------------- # tv.data<-read.table("C:/R/data/tv.dat") ## ---- tv3--------------------------------------------------------------------- TV <- array(tv.data[,5], dim=c(5,11,5,3)) dimnames(TV) <- list(c("Monday","Tuesday","Wednesday","Thursday","Friday"), c("8:00","8:15","8:30","8:45","9:00","9:15","9:30", "9:45","10:00","10:15","10:30"), c("ABC","CBS","NBC","Fox","Other"), c("Off","Switch","Persist")) names(dimnames(TV))<-c("Day", "Time", "Network", "State") ## ---- tv3a,eval=FALSE--------------------------------------------------------- # TV <- xtabs(V5 ~ ., data=tv.data) # dimnames(TV) <- list(Day = c("Monday","Tuesday","Wednesday","Thursday","Friday"), # Time = c("8:00","8:15","8:30","8:45","9:00","9:15","9:30", # "9:45","10:00","10:15","10:30"), # Network = c("ABC","CBS","NBC","Fox","Other"), # State = c("Off","Switch","Persist")) # # # table dimensions # dim(TV) ## ---- tv4--------------------------------------------------------------------- TV2 <- TV[,,1:3,] # keep only ABC, CBS, NBC TV2 <- TV2[,,,3] # keep only Persist -- now a 3 way table structable(TV2) ## ---- tv5--------------------------------------------------------------------- TV.df <- as.data.frame.table(TV2) levels(TV.df$Time) <- c(rep("8:00", 2), rep("8:30", 2), rep("9:00", 2), rep("9:30", 2), rep("10:00",2), "10:30" ) TV3 <- xtabs(Freq ~ Day + Time + Network, TV.df) structable(Day ~ Time+Network, TV3) ## ----tv-mosaic1, fig.height=6, fig.width=7------------------------------------ mosaic(TV3, shade = TRUE, labeling = labeling_border(rot_labels = c(0, 0, 0, 90)))
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/creating.R
--- title: "Creating and manipulating frequency tables" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Creating and manipulating frequency tables} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut01-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Old Sweave options # \SweaveOpts{engine=R,eps=TRUE,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{engine=R,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{prefix.string=fig/vcd-tut,eps=FALSE} # \SweaveOpts{keep.source=TRUE} # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ``` R provides many methods for creating frequency and contingency tables. Several are described below. In the examples below, we use some real examples and some anonymous ones, where the variables `A`, `B`, and `C` represent categorical variables, and `X` represents an arbitrary R data object. ## Forms of frequency data The first thing you need to know is that categorical data can be represented in three different forms in R, and it is sometimes necessary to convert from one form to another, for carrying out statistical tests, fitting models or visualizing the results. Once a data object exists in R, you can examine its complete structure with the `str()` function, or view the names of its components with the `names()` function. ### Case form Categorical data in case form are simply data frames containing individual observations, with one or more factors, used as the classifying variables. In case form, there may also be numeric covariates. The total number of observations is `nrow(X)`, and the number of variables is `ncol(X)`. ***Example***: The `Arthritis` data is available in case form in the `vcd` package. There are two explanatory factors: `Treatment` and `Sex`. `Age` is a numeric covariate, and `Improved` is the response--- an ordered factor, with levels `r paste(levels(Arthritis$Improved),collapse=' < ')`. Excluding `Age`, this represents a $2 \times 2 \times 3$ contingency table for `Treatment`, `Sex` and `Improved`, but in case form. ```{r, case-form} names(Arthritis) # show the variables str(Arthritis) # show the structure head(Arthritis,5) # first 5 observations, same as Arthritis[1:5,] ``` ### Frequency form Data in frequency form is also a data frame containing one or more factors, and a frequency variable, often called `Freq` or `count`. The total number of observations is: `sum(X$Freq)`, `sum(X[,"Freq"])` or some equivalent form. The number of cells in the table is given by `nrow(X)`. ***Example***: For small frequency tables, it is often convenient to enter them in frequency form using `expand.grid()` for the factors and `c()` to list the counts in a vector. The example below, from [@vcd:Agresti:2002] gives results for the 1991 General Social Survey, with respondents classified by sex and party identification. ```{r, frequency-form} # Agresti (2002), table 3.11, p. 106 GSS <- data.frame( expand.grid(sex = c("female", "male"), party = c("dem", "indep", "rep")), count = c(279,165,73,47,225,191)) GSS names(GSS) str(GSS) sum(GSS$count) ``` ### Table form Table form data is represented by a `matrix`, `array` or `table` object, whose elements are the frequencies in an $n$-way table. The variable names (factors) and their levels are given by `dimnames(X)`. The total number of observations is `sum(X)`. The number of dimensions of the table is `length(dimnames(X))`, and the table sizes are given by `sapply(dimnames(X), length)`. ***Example***: The `HairEyeColor` is stored in table form in `vcd`. ```{r, table-form1} str(HairEyeColor) # show the structure sum(HairEyeColor) # number of cases sapply(dimnames(HairEyeColor), length) # table dimension sizes ``` ***Example***: Enter frequencies in a matrix, and assign `dimnames`, giving the variable names and category labels. Note that, by default, `matrix()` uses the elements supplied by *columns* in the result, unless you specify `byrow=TRUE`. ```{r, table-form2} # A 4 x 4 table Agresti (2002, Table 2.8, p. 57) Job Satisfaction JobSat <- matrix(c( 1, 2, 1, 0, 3, 3, 6, 1, 10,10,14, 9, 6, 7,12,11), 4, 4) dimnames(JobSat) = list( income = c("< 15k", "15-25k", "25-40k", "> 40k"), satisfaction = c("VeryD", "LittleD", "ModerateS", "VeryS") ) JobSat ``` `JobSat` is a **matrix**, not an object of `class("table")`, and some functions are happier with tables than matrices. You can coerce it to a table with `as.table()`, ```{r, table-form3} JobSat <- as.table(JobSat) str(JobSat) ``` ## Ordered factors and reordered tables {#sec:ordered-factors} In table form, the values of the table factors are ordered by their position in the table. Thus in the `JobSat` data, both `income` and `satisfaction` represent ordered factors, and the *positions* of the values in the rows and columns reflects their ordered nature. Yet, for analysis, there are times when you need *numeric* values for the levels of ordered factors in a table, e.g., to treat a factor as a quantitative variable. In such cases, you can simply re-assign the `dimnames` attribute of the table variables. For example, here, we assign numeric values to `income` as the middle of their ranges, and treat `satisfaction` as equally spaced with integer scores. ```{r, relevel, eval=FALSE} dimnames(JobSat)$income <- c(7.5,20,32.5,60) dimnames(JobSat)$satisfaction <- 1:4 ``` For the `HairEyeColor` data, hair color and eye color are ordered arbitrarily. For visualizing the data using mosaic plots and other methods described below, it turns out to be more useful to assure that both hair color and eye color are ordered from dark to light. Hair colors are actually ordered this way already, and it is easiest to re-order eye colors by indexing. Again `str()` is your friend. ```{r, reorder1} HairEyeColor <- HairEyeColor[, c(1,3,4,2), ] str(HairEyeColor) ``` This is also the order for both hair color and eye color shown in the result of a correspondence analysis (@ref(fig:ca-haireye) below. With data in case form or frequency form, when you have ordered factors represented with character values, you must ensure that they are treated as ordered in R. <!-- \footnote{In SAS, many procedures offer the option --> <!-- `order = data | internal | formatted` to allow character values --> <!-- to be ordered according to (a) their order in the data set, (b) --> <!-- sorted internal value, or (c) sorted formatted representation --> <!-- provided by a SAS format. --> <!-- } --> Imagine that the `Arthritis` data was read from a text file. By default the `Improved` will be ordered alphabetically: `Marked`, `None`, `Some` --- not what we want. In this case, the function `ordered()` (and others) can be useful. ```{r, reorder2, echo=TRUE, eval=FALSE} Arthritis <- read.csv("arthritis.txt",header=TRUE) Arthritis$Improved <- ordered(Arthritis$Improved, levels=c("None", "Some", "Marked") ) ``` The dataset `Arthritis` in the `vcd` package is a data.frame in this form With this order of `Improved`, the response in this data, a mosaic display of `Treatment` and `Improved` (@ref(fig:arthritis) shows a clearly interpretable pattern. The original version of `mosaic` in the `vcd` package required the input to be a contingency table in array form, so we convert using `xtabs()`. <!-- ```{r Arthritis, height=6, width=7, fig.cap="Mosaic plot for the `Arthritis` data ..."} --> ```{r} #| Arthritis, #| fig.height = 6, #| fig.width = 6, #| fig.cap = "Mosaic plot for the `Arthritis` data, showing the marginal model of independence for Treatment and Improved. Age, a covariate, and Sex are ignored here." data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) mosaic(art, gp = shading_max, split_vertical = TRUE, main="Arthritis: [Treatment] [Improved]") ``` Several data sets in the package illustrate the salutary effects of reordering factor levels in mosaic displays and other analyses. See: * `help(AirCrash)` * `help(Glass)` * `help(HouseTasks)` The [seriate](https://CRAN.R-project.org/package=seriation) package now contains a general method to permute the row and column variables in a table according to the result of a correspondence analysis, using scores on the first CA dimension. ### Re-ordering dimensions Finally, there are situations where, particularly for display purposes, you want to re-order the *dimensions* of an $n$-way table, or change the labels for the variables or levels. This is easy when the data are in table form: `aperm()` permutes the dimensions, and assigning to `names` and `dimnames` changes variable names and level labels respectively. We will use the following version of `UCBAdmissions` in \@ref(sec:mantel) below. ^[Changing `Admit` to `Admit?` might be useful for display purposes, but is dangerous--- because it is then difficult to use that variable name in a model formula. See \@ref(sec:tips) for options `labeling_args` and `set_labels`to change variable and level names for displays in the `strucplot` framework.] ```{r, reorder3} UCB <- aperm(UCBAdmissions, c(2, 1, 3)) dimnames(UCB)[[2]] <- c("Yes", "No") names(dimnames(UCB)) <- c("Sex", "Admit?", "Department") # display as a flattened table stats::ftable(UCB) ``` ## `structable()` {#sec:structable} For 3-way and larger tables the `structable()` function in `vcd` provides a convenient and flexible tabular display. The variables assigned to the rows and columns of a two-way display can be specified by a model formula. ```{r, structable} structable(HairEyeColor) # show the table: default structable(Hair+Sex ~ Eye, HairEyeColor) # specify col ~ row variables ``` It also returns an object of class `"structable"` which may be plotted with `mosaic()` (not shown here). ```{r, structable1,eval=FALSE} HSE < - structable(Hair+Sex ~ Eye, HairEyeColor) # save structable object mosaic(HSE) # plot it ``` ## `table()` and friends {#sec:table} You can generate frequency tables from factor variables using the `table()` function, tables of proportions using the `prop.table()` function, and marginal frequencies using `margin.table()`. For these examples, create some categorical vectors: ```{r, table-setup} n=500 A <- factor(sample(c("a1","a2"), n, rep=TRUE)) B <- factor(sample(c("b1","b2"), n, rep=TRUE)) C <- factor(sample(c("c1","c2"), n, rep=TRUE)) mydata <- data.frame(A,B,C) ``` These lines illustrate `table`-related functions: ```{r, table-ex1} # 2-Way Frequency Table attach(mydata) mytable <- table(A,B) # A will be rows, B will be columns mytable # print table margin.table(mytable, 1) # A frequencies (summed over B) margin.table(mytable, 2) # B frequencies (summed over A) prop.table(mytable) # cell percentages prop.table(mytable, 1) # row percentages prop.table(mytable, 2) # column percentages ``` `table()` can also generate multidimensional tables based on 3 or more categorical variables. In this case, you can use the `ftable()` or `structable()` function to print the results more attractively. ```{r, table-ex2} # 3-Way Frequency Table mytable <- table(A, B, C) ftable(mytable) ``` `table()` ignores missing values by default. To include `NA` as a category in counts, include the table option `exclude=NULL` if the variable is a vector. If the variable is a factor you have to create a new factor using \code{newfactor <- factor(oldfactor, exclude=NULL)}. ## `xtabs()` {#sec:xtabs} The `xtabs()` function allows you to create cross-tabulations of data using formula style input. This typically works with case-form data supplied in a data frame or a matrix. The result is a contingency table in array format, whose dimensions are determined by the terms on the right side of the formula. ```{r, xtabs-ex1} # 3-Way Frequency Table mytable <- xtabs(~A+B+C, data=mydata) ftable(mytable) # print table summary(mytable) # chi-square test of indepedence ``` If a variable is included on the left side of the formula, it is assumed to be a vector of frequencies (useful if the data have already been tabulated in frequency form). ```{r, xtabs-ex2} (GSStab <- xtabs(count ~ sex + party, data=GSS)) summary(GSStab) ``` ## Collapsing over table factors: `aggregate()`, `margin.table()` and `apply()` It sometimes happens that we have a data set with more variables or factors than we want to analyse, or else, having done some initial analyses, we decide that certain factors are not important, and so should be excluded from graphic displays by collapsing (summing) over them. For example, mosaic plots and fourfold displays are often simpler to construct from versions of the data collapsed over the factors which are not shown in the plots. The appropriate tools to use again depend on the form in which the data are represented--- a case-form data frame, a frequency-form data frame (`aggregate()`), or a table-form array or table object (`margin.table()` or `apply()`). When the data are in frequency form, and we want to produce another frequency data frame, `aggregate()` is a handy tool, using the argument `FUN=sum` to sum the frequency variable over the factors *not* mentioned in the formula. ***Example***: The data frame `DaytonSurvey` in the `vcdExtra` package represents a $2^5$ table giving the frequencies of reported use (``ever used?'') of alcohol, cigarettes and marijuana in a sample of high school seniors, also classified by sex and race. ```{r, dayton1} data("DaytonSurvey", package="vcdExtra") str(DaytonSurvey) head(DaytonSurvey) ``` To focus on the associations among the substances, we want to collapse over sex and race. The right-hand side of the formula used in the call to `aggregate()` gives the factors to be retained in the new frequency data frame, `Dayton.ACM.df`. ```{r, dayton2} # data in frequency form # collapse over sex and race Dayton.ACM.df <- aggregate(Freq ~ cigarette+alcohol+marijuana, data=DaytonSurvey, FUN=sum) Dayton.ACM.df ``` When the data are in table form, and we want to produce another table, `apply()` with `FUN=sum` can be used in a similar way to sum the table over dimensions not mentioned in the `MARGIN` argument. `margin.table()` is just a wrapper for `apply()` using the `sum()` function. ***Example***: To illustrate, we first convert the `DaytonSurvey` to a 5-way table using `xtabs()`, giving `Dayton.tab`. ```{r, dayton3} # in table form Dayton.tab <- xtabs(Freq ~ cigarette+alcohol+marijuana+sex+race, data=DaytonSurvey) structable(cigarette+alcohol+marijuana ~ sex+race, data=Dayton.tab) ``` Then, use `apply()` on `Dayton.tab` to give the 3-way table `Dayton.ACM.tab` summed over sex and race. The elements in this new table are the column sums for `Dayton.tab` shown by `structable()` just above. ```{r, dayton4} # collapse over sex and race Dayton.ACM.tab <- apply(Dayton.tab, MARGIN=1:3, FUN=sum) Dayton.ACM.tab <- margin.table(Dayton.tab, 1:3) # same result structable(cigarette+alcohol ~ marijuana, data=Dayton.ACM.tab) ``` Many of these operations can be performed using the `**ply()` functions in the [`plyr`]( https://CRAN.R-project.org/package=plyr) package. For example, with the data in a frequency form data frame, use `ddply()` to collapse over unmentioned factors, and `plyr::summarise()` as the function to be applied to each piece. <!-- \footnote{ --> <!-- Ugh. This `plyr` function clashes with a function of the same name in `vcdExtra`. --> <!-- In this document I will use the explicit double-colon notation to keep them --> <!-- separate. --> <!-- } --> ```{r, dayton5} library(plyr) Dayton.ACM.df <- plyr::ddply(DaytonSurvey, .(cigarette, alcohol, marijuana), plyr::summarise, Freq=sum(Freq)) Dayton.ACM.df ``` ## Collapsing table levels: `collapse.table()` A related problem arises when we have a table or array and for some purpose we want to reduce the number of levels of some factors by summing subsets of the frequencies. For example, we may have initially coded Age in 10-year intervals, and decide that, either for analysis or display purposes, we want to reduce Age to 20-year intervals. The `collapse.table()` function in `vcdExtra` was designed for this purpose. ***Example***: Create a 3-way table, and collapse Age from 10-year to 20-year intervals. First, we generate a $2 \times 6 \times 3$ table of random counts from a Poisson distribution with mean of 100. ```{r, collapse1} # create some sample data in frequency form sex <- c("Male", "Female") age <- c("10-19", "20-29", "30-39", "40-49", "50-59", "60-69") education <- c("low", 'med', 'high') data <- expand.grid(sex=sex, age=age, education=education) counts <- rpois(36, 100) # random Possion cell frequencies data <- cbind(data, counts) # make it into a 3-way table t1 <- xtabs(counts ~ sex + age + education, data=data) structable(t1) ``` Now collapse `age` to 20-year intervals, and `education` to 2 levels. In the arguments, levels of `age` and `education` given the same label are summed in the resulting smaller table. ```{r, collapse2} # collapse age to 3 levels, education to 2 levels t2 <- collapse.table(t1, age=c("10-29", "10-29", "30-49", "30-49", "50-69", "50-69"), education=c("<high", "<high", "high")) structable(t2) ``` ## Collapsing table levels: `dplyr` For data sets in frequency form or case form, factor levels can be collapsed by recoding the levels to some grouping. One handy function for this is `dplyr::case_match()` ***Example***: The `vcdExtra::Titanicp` data set contains information on 1309 passengers on the _RMS Titanic_, including `sibsp`, the number of (0:8) siblings or spouses aboard, and `parch` (0:6), the number of parents or children aboard, but the table is quite sparse. ```{r titanicp1} table(Titanicp$sibsp, Titanicp$parch) ``` For purposes of analysis, we might want to collapse both of these to the levels `0, 1, 2+`. Here's how: ```{r titanicp2} library(dplyr) Titanicp <- Titanicp |> mutate(sibspF = case_match(sibsp, 0 ~ "0", 1 ~ "1", 2:max(sibsp) ~ "2+")) |> mutate(sibspF = ordered(sibspF)) |> mutate(parchF = case_match(parch, 0 ~ "0", 1 ~ "1", 2:max(parch) ~ "2+")) |> mutate(parchF = ordered(parchF)) table(Titanicp$sibspF, Titanicp$parchF) ``` `car::recode()` is a similar function, but with a less convenient interface. The [`forcats`]( https://CRAN.R-project.org/package=forcats) package provides a collection of functions for reordering the levels of a factor or grouping categories according to their frequency: * `forcats::fct_reorder()`: Reorder a factor by another variable. * `forcats::fct_infreq()`: Reorder a factor by the frequency of values. * `forcats::fct_relevel()`: Change the order of a factor by hand. * `forcats::fct_lump()`: Collapse the least/most frequent values of a factor into “other”. * `forcats::fct_collapse()`: Collapse factor levels into manually defined groups. * `forcats::fct_recode()`: Change factor levels by hand. ## Converting among frequency tables and data frames As we've seen, a given contingency table can be represented equivalently in different forms, but some R functions were designed for one particular representation. The table below shows some handy tools for converting from one form to another. <!-- [htb] --> <!-- \caption{Tools for converting among different forms for categorical data} {#tab:convert} --> <!-- {llll} --> <!-- \hline --> <!-- & \multicolumn{3}{c}{**To this**} \\ --> <!-- **From this** & Case form & Frequency form & Table form \\ --> <!-- \hline --> <!-- Case form & noop & `xtabs(~A+B)` & `table(A,B)` \\ --> <!-- Frequency form & `expand.dft(X)` & noop & `xtabs(count~A+B)`\\ --> <!-- Table form & `expand.dft(X)` & `as.data.frame(X)` & noop \\ --> <!-- \hline --> | **From this** | | **To this** | | |:-----------------|:--------------------|:---------------------|-------------------| | | _Case form_ | _Frequency form_ | _Table form_ | | _Case form_ | noop | `xtabs(~A+B)` | `table(A,B)` | | _Frequency form_ | `expand.dft(X)` | noop | `xtabs(count~A+B)`| | _Table form_ | `expand.dft(X)` | `as.data.frame(X)` | noop | For example, a contingency table in table form (an object of `class(table)`) can be converted to a data.frame with `as.data.frame()`. ^[Because R is object-oriented, this is actually a short-hand for the function `as.data.frame.table()`.] The resulting `data.frame` contains columns representing the classifying factors and the table entries (as a column named by the `responseName` argument, defaulting to `Freq`. This is the inverse of `xtabs()`. ***Example***: Convert the `GSStab` in table form to a data.frame in frequency form. ```{r, convert-ex1} as.data.frame(GSStab) ``` ***Example***: Convert the `Arthritis` data in case form to a 3-way table of `Treatment` $\times$ `Sex` $\times$ `Improved`. Note the use of `with()` to avoid having to use `Arthritis\$Treatment` etc. within the call to `table()`.% ^[`table()` does not allow a `data` argument to provide an environment in which the table variables are to be found. In the examples in \@ref(sec:table) I used `attach(mydata)` for this purpose, but `attach()` leaves the variables in the global environment, while `with()` just evaluates the `table()` expression in a temporary environment of the data.] ```{r, convert-ex2} Art.tab <- with(Arthritis, table(Treatment, Sex, Improved)) str(Art.tab) ftable(Art.tab) ``` There may also be times that you will need an equivalent case form `data.frame` with factors representing the table variables rather than the frequency table. For example, the `mca()` function in package `MASS` only operates on data in this format. Marc Schwartz initially provided code for `expand.dft()` on the Rhelp mailing list for converting a table back into a case form `data.frame`. This function is included in `vcdExtra`. ***Example***: Convert the `Arthritis` data in table form (`Art.tab`) back to a `data.frame` in case form, with factors `Treatment`, `Sex` and `Improved`. ```{r, convert-ex3} Art.df <- expand.dft(Art.tab) str(Art.df) ``` ## A complex example {#sec:complex} If you've followed so far, you're ready for a more complicated example. The data file, `tv.dat` represents a 4-way table of size $5 \times 11 \times 5 \times 3$ where the table variables (unnamed in the file) are read as `V1` -- `V4`, and the cell frequency is read as `V5`. The file, stored in the `doc/extdata` directory of `vcdExtra`, can be read as follows: ```{r, tv1} tv.data<-read.table(system.file("extdata","tv.dat", package="vcdExtra")) head(tv.data,5) ``` For a local file, just use `read.table()` in this form: ```{r, tv2,eval=FALSE} tv.data<-read.table("C:/R/data/tv.dat") ``` The data `tv.dat` came from the initial implementation of mosaic displays in R by Jay Emerson. In turn, they came from the initial development of mosaic displays [@vcd:Hartigan+Kleiner:1984] that illustrated the method with data on a large sample of TV viewers whose behavior had been recorded for the Neilsen ratings. This data set contains sample television audience data from Neilsen Media Research for the week starting November 6, 1995. The table variables are: * `V1`-- values 1:5 correspond to the days Monday--Friday; * `V2`-- values 1:11 correspond to the quarter hour times 8:00PM through 10:30PM; * `V3`-- values 1:5 correspond to ABC, CBS, NBC, Fox, and non-network choices; * `V4`-- values 1:3 correspond to transition states: turn the television Off, Switch channels, or Persist in viewing the current channel. We are interested just the cell frequencies, and rely on the facts that the (a) the table is complete--- there are no missing cells, so `nrow(tv.data)` = `r nrow(tv.data)`; (b) the observations are ordered so that `V1` varies most rapidly and `V4` most slowly. From this, we can just extract the frequency column and reshape it into an array. [That would be dangerous if any observations were out of order.] ```{r, tv3} TV <- array(tv.data[,5], dim=c(5,11,5,3)) dimnames(TV) <- list(c("Monday","Tuesday","Wednesday","Thursday","Friday"), c("8:00","8:15","8:30","8:45","9:00","9:15","9:30", "9:45","10:00","10:15","10:30"), c("ABC","CBS","NBC","Fox","Other"), c("Off","Switch","Persist")) names(dimnames(TV))<-c("Day", "Time", "Network", "State") ``` More generally (even if there are missing cells), we can use `xtabs()` (or `plyr::daply()`) to do the cross-tabulation, using `V5` as the frequency variable. Here's how to do this same operation with `xtabs()`: ```{r, tv3a,eval=FALSE} TV <- xtabs(V5 ~ ., data=tv.data) dimnames(TV) <- list(Day = c("Monday","Tuesday","Wednesday","Thursday","Friday"), Time = c("8:00","8:15","8:30","8:45","9:00","9:15","9:30", "9:45","10:00","10:15","10:30"), Network = c("ABC","CBS","NBC","Fox","Other"), State = c("Off","Switch","Persist")) # table dimensions dim(TV) ``` But this 4-way table is too large and awkward to work with. Among the networks, Fox and Other occur infrequently. We can also cut it down to a 3-way table by considering only viewers who persist with the current station. ^[This relies on the fact that that indexing an array drops dimensions of length 1 by default, using the argument `drop=TRUE`; the result is coerced to the lowest possible dimension.] ```{r, tv4} TV2 <- TV[,,1:3,] # keep only ABC, CBS, NBC TV2 <- TV2[,,,3] # keep only Persist -- now a 3 way table structable(TV2) ``` Finally, for some purposes, we might want to collapse the 11 times into a smaller number. Half-hour time slots make more sense. Here, we use `as.data.frame.table()` to convert the table back to a data frame, `levels()` to re-assign the values of `Time`, and finally, `xtabs()` to give a new, collapsed frequency table. ```{r, tv5} TV.df <- as.data.frame.table(TV2) levels(TV.df$Time) <- c(rep("8:00", 2), rep("8:30", 2), rep("9:00", 2), rep("9:30", 2), rep("10:00",2), "10:30" ) TV3 <- xtabs(Freq ~ Day + Time + Network, TV.df) structable(Day ~ Time+Network, TV3) ``` We've come this far, so we might as well show a mosaic display. This is analogous to that used by @vcd:Hartigan+Kleiner:1984. ```{r tv-mosaic1, fig.height=6, fig.width=7} mosaic(TV3, shade = TRUE, labeling = labeling_border(rot_labels = c(0, 0, 0, 90))) ``` This mosaic displays can be read at several levels, corresponding to the successive splits of the tiles and the residual shading. Several trends are clear for viewers who persist: * Overall, there are about the same number of viewers on each weekday, with slightly more on Thursday. * Looking at time slots, viewership is slightly greater from 9:00 - 10:00 overall and also 8:00 - 9:00 on Thursday and Friday From the residual shading of the tiles: * Monday: CBS dominates in all time slots. * Tuesday" ABC and CBS dominate after 9:00 * Thursday: is a largely NBC day * Friday: ABC dominates in the early evening <!-- ```{r, tv4} --> <!-- TV.df <- as.data.frame.table(TV) --> <!-- levels(TV.df$Time) <- c(rep("8:00-8:59",4), --> <!-- rep("9:00-9:59",4), --> <!-- rep("10:00-10:44",3)) --> <!-- TV3 <- xtabs(Freq ~ Day + Time + Network, TV.df) --> <!-- structable(Day ~ Time+Network, TV3) --> <!-- ``` --> <!-- Whew! See \figref{fig:TV-mosaic} for a mosaic plot of the `TV3` data. --> <!-- The table is too large to display conveniently, but we can show a subtable --> <!-- by selecting the indices. This call to `ftable()` subsets the first three --> <!-- levels of each factor. --> <!-- ```{r tv4} --> <!-- ftable(TV[1:3,1:3,1:3,1:3], col.vars = 3:4) --> <!-- ``` --> <!-- We've come this far, so we might as well show a mosaic display. This is analogous to that used by --> <!-- @vcd:Hartigan+Kleiner:1984. The result is too complex to see very much. It would be useful to simplify --> <!-- the table by collapsing one or more of the table dimensions, e.g., `Time`. --> <!-- ```{r tv-mosaic2, fig.height=7, fig.width=7} --> <!-- mosaic(TV[,,1:4,], shade=TRUE, --> <!-- labeling_args = list(abbreviate_labs = c(8,5,1,1))) --> <!-- ``` --> # References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/creating.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/datasets-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") ## ----load--------------------------------------------------------------------- library(dplyr) library(tidyr) library(readxl) ## ----read-datasets------------------------------------------------------------ dsets_tagged <- read_excel(here::here("inst", "extdata", "vcdExtra-datasets.xlsx"), sheet="vcdExtra-datasets") dsets_tagged <- dsets_tagged |> dplyr::select(-Title, -dim) |> dplyr::rename(dataset = Item) head(dsets_tagged) ## ----split-tags--------------------------------------------------------------- dset_split <- dsets_tagged |> tidyr::separate_longer_delim(tags, delim = ";") |> dplyr::mutate(tag = stringr::str_trim(tags)) |> dplyr::select(-tags) #' ## collapse the rows for the same tag tag_dset <- dset_split |> arrange(tag) |> dplyr::group_by(tag) |> dplyr::summarise(datasets = paste(dataset, collapse = "; ")) |> ungroup() # get a list of the unique tags unique(tag_dset$tag) ## ----read-tags---------------------------------------------------------------- tags <- read_excel(here::here("inst", "extdata", "vcdExtra-datasets.xlsx"), sheet="tags") head(tags) ## ----join-tags---------------------------------------------------------------- tag_dset <- tag_dset |> dplyr::left_join(tags, by = "tag") |> dplyr::relocate(topic, .after = tag) tag_dset |> dplyr::select(-tag) |> head() ## ----add-links---------------------------------------------------------------- add_links <- function(dsets, style = c("reference", "help", "rdrr.io"), sep = "; ") { style <- match.arg(style) names <- stringr::str_split_1(dsets, sep) names <- dplyr::case_when( style == "help" ~ glue::glue("[{names}](help({names}))"), style == "reference" ~ glue::glue("[{names}](../reference/{names}.html)"), style == "rdrr.io" ~ glue::glue("[{names}](https://rdrr.io/cran/vcdExtra/man/{names}.html)") ) glue::glue_collapse(names, sep = sep) } ## ----kable-------------------------------------------------------------------- tag_dset |> dplyr::select(-tag) |> dplyr::mutate(datasets = purrr::map(datasets, add_links)) |> knitr::kable()
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/datasets.R
--- title: "Datasets for categorical data analysis" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Datasets for categorical data analysis} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/datasets-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") ``` The `vcdExtra` package contains `r nrow(vcdExtra::datasets("vcdExtra"))` datasets, taken from the literature on categorical data analysis, and selected to illustrate various methods of analysis and data display. These are in addition to the `r nrow(vcdExtra::datasets("vcd"))` datasets in the [vcd package](https://cran.r-project.org/package=vcd). To make it easier to find those which illustrate a particular method, the datasets in `vcdExtra` have been classified using method tags. This vignette creates an "inverse table", listing the datasets that apply to each method. It also illustrates a general method for classifying datasets in R packages. ```{r load} library(dplyr) library(tidyr) library(readxl) ``` ## Processing tags Using the result of `vcdExtra::datasets(package="vcdExtra")` I created a spreadsheet, `vcdExtra-datasets.xlsx`, and then added method tags. ```{r read-datasets} dsets_tagged <- read_excel(here::here("inst", "extdata", "vcdExtra-datasets.xlsx"), sheet="vcdExtra-datasets") dsets_tagged <- dsets_tagged |> dplyr::select(-Title, -dim) |> dplyr::rename(dataset = Item) head(dsets_tagged) ``` To invert the table, need to split tags into separate observations, then collapse the rows for the same tag. ```{r split-tags} dset_split <- dsets_tagged |> tidyr::separate_longer_delim(tags, delim = ";") |> dplyr::mutate(tag = stringr::str_trim(tags)) |> dplyr::select(-tags) #' ## collapse the rows for the same tag tag_dset <- dset_split |> arrange(tag) |> dplyr::group_by(tag) |> dplyr::summarise(datasets = paste(dataset, collapse = "; ")) |> ungroup() # get a list of the unique tags unique(tag_dset$tag) ``` ## Make this into a nice table Another sheet in the spreadsheet gives a more descriptive `topic` for corresponding to each tag. ```{r read-tags} tags <- read_excel(here::here("inst", "extdata", "vcdExtra-datasets.xlsx"), sheet="tags") head(tags) ``` Now, join this with the `tag_dset` created above. ```{r join-tags} tag_dset <- tag_dset |> dplyr::left_join(tags, by = "tag") |> dplyr::relocate(topic, .after = tag) tag_dset |> dplyr::select(-tag) |> head() ``` ### Add links to `help()` We're almost there. It would be nice if the dataset names could be linked to their documentation. This function is designed to work with the `pkgdown` site. There are different ways this can be done, but what seems to work is a link to `../reference/{dataset}.html` Unfortunately, this won't work in the actual vignette. ```{r add-links} add_links <- function(dsets, style = c("reference", "help", "rdrr.io"), sep = "; ") { style <- match.arg(style) names <- stringr::str_split_1(dsets, sep) names <- dplyr::case_when( style == "help" ~ glue::glue("[{names}](help({names}))"), style == "reference" ~ glue::glue("[{names}](../reference/{names}.html)"), style == "rdrr.io" ~ glue::glue("[{names}](https://rdrr.io/cran/vcdExtra/man/{names}.html)") ) glue::glue_collapse(names, sep = sep) } ``` ## Make the table {#table} Use `purrr::map()` to apply `add_links()` to all the datasets for each tag. (`mutate(datasets = add_links(datasets))` by itself doesn't work.) ```{r kable} tag_dset |> dplyr::select(-tag) |> dplyr::mutate(datasets = purrr::map(datasets, add_links)) |> knitr::kable() ``` Voila!
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/datasets.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/demo-housing-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # colorize text colorize <- function(x, color) { if (knitr::is_latex_output()) { sprintf("\\textcolor{%s}{%s}", color, x) } else if (knitr::is_html_output()) { sprintf("<span style='color: %s;'>%s</span>", color, x) } else x } ## ----------------------------------------------------------------------------- library(vcdExtra) library(MASS) library(effects) ## ----housing------------------------------------------------------------------ data(housing, package="MASS") str(housing) ## ----------------------------------------------------------------------------- levels(housing$Sat) levels(housing$Infl) ## ----house.null--------------------------------------------------------------- house.null <- glm(Freq ~ Sat + Infl + Type + Cont, family = poisson, data = housing) ## ----house.glm0--------------------------------------------------------------- house.glm0 <- glm(Freq ~ Sat + Infl*Type*Cont, family = poisson, data = housing) ## ----anova-------------------------------------------------------------------- anova(house.null, house.glm0, test = "Chisq") ## ----------------------------------------------------------------------------- # labeling_args for mosaic() largs <- list(set_varnames = c( Infl="Influence on management", Cont="Contact among residents", Type="Type of dwelling", Sat="Satisfaction"), abbreviate=c(Type=3)) mosaic(house.glm0, labeling_args=largs, main='Baseline model: [ITC][Sat]') ## ----mosaic-glm0b------------------------------------------------------------- mosaic(house.glm0, formula = ~ Type + Infl + Cont + Sat, labeling_args=largs, main=paste('Baseline model: [ITC][Sat],', modFit(house.glm0)) ) ## ----addterm------------------------------------------------------------------ MASS::addterm(house.glm0, ~ . + Sat:(Infl + Type + Cont), test = "Chisq") ## ----house-glm1--------------------------------------------------------------- house.glm1 <- update(house.glm0, . ~ . + Sat*(Infl + Type + Cont)) ## ----house-loglm1------------------------------------------------------------- (house.loglm1 <- MASS::loglm(Freq ~ Infl * Type * Cont + Sat*(Infl + Type + Cont), data = housing)) ## ----------------------------------------------------------------------------- anova(house.glm0, house.glm1, test="Chisq") ## ----mosaic-glm1-------------------------------------------------------------- mosaic(house.glm1, labeling_args=largs, main=paste('Model [IS][TS][CS],', modFit(house.glm1) ), gp=shading_Friendly) ## ----dropterm----------------------------------------------------------------- MASS::dropterm(house.glm1, test = "Chisq") ## ----addterm1----------------------------------------------------------------- MASS::addterm(house.glm1, ~. + Sat:(Infl + Type + Cont)^2, test = "Chisq") ## ----------------------------------------------------------------------------- house.glm2 <- update(house.glm1, . ~ . + Sat:Infl:Type) ## ----lrstats------------------------------------------------------------------ LRstats(house.glm0, house.glm1, house.glm2)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/demo-housing.R
--- title: "Demo - Housing Data" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Demo - Housing Data} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/demo-housing-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # colorize text colorize <- function(x, color) { if (knitr::is_latex_output()) { sprintf("\\textcolor{%s}{%s}", color, x) } else if (knitr::is_html_output()) { sprintf("<span style='color: %s;'>%s</span>", color, x) } else x } ``` This vignette was one of a series of `demo()` files in the package. It is still there as `demo("housing")`, but is now presented here with additional commentary and analysis, designed to highlight some aspects of analysis of categorical data and graphical display. ## Load packages I'll use the following packages in this vignette. ```{r} library(vcdExtra) library(MASS) library(effects) ``` ## Housing data The content here is the dataset `MASS::housing`, giving a 4-way, $3 \times 3 \times 4 \times 2$ frequency table of 1681 individuals from the *Copenhagen Housing Conditions Survey*, classified by their: * Satisfaction (`Sat`) with their housing circumstances (low, medium or high), * `Type` of rental dwelling (Tower, Apartment, Atrium or Terrace) * perceived influence (`Infl`) on management of the property (low, medium, high), and * degree of contact (`Cont`) with other residents (low or high) Load the data: ```{r housing} data(housing, package="MASS") str(housing) ``` ### Variables, levels and models Satisfaction (`Sat`) of these householders with their present housing circumstances is the **outcome variable** here. For purposes of analysis, note that `Sat` is an ordered factor with levels `"Low" < "Medium" < "High"`. Note also that Influence, with the same levels is just a "Factor", not an ordered one. I consider here just models using `glm(..., family=poisson)` or the equivalent in `MASS::loglm()`. The ordering of factor levels is important in graphical displays. We don't want to see them ordered alphabetically, "High", "Low", "Medium". The `housing` data.frame was constructed so that the levels of `Sat` and `Infl` appear in the dataset in their appropriate order. ```{r} levels(housing$Sat) levels(housing$Infl) ``` Other models, e.g., the **proportional odds** model, fit using `MASS:polr()` can take the ordinal nature of satisfaction into account. In `glm()` one could re-assign `Infl` as an ordered factor and examine linear vs. non-linear associations for this factor. But I don't do this here. ## Null model The most ignorant model asserts that all the table factors are mutually independent. In symbolic notation, this is `[S] [I] [T] [C]` where all terms in separate `[ ]` are supposed to be independent. This is `Freq ~ Sat + Infl + Type + Cont` as a formula for `glm()`. ```{r house.null} house.null <- glm(Freq ~ Sat + Infl + Type + Cont, family = poisson, data = housing) ``` ## Baseline model When `Sat` is the outcome variable, a minimal **baseline model** should allow for all associations among the predictors, symbolized as `[S] [I T C]`. That is, Influence, Type and Contact may be associated in arbitrary ways, just as multiple predictors can be correlated in regression models. In this framework, what remains to be explained is whether/how `Sat` depends on the combinations of the other variables. The baseline model therefore includes the full three-way term for the predictors. ```{r house.glm0} house.glm0 <- glm(Freq ~ Sat + Infl*Type*Cont, family = poisson, data = housing) ``` Both of these models fit terribly, but we can always use `anova(mod1, mod2,...)` to compare the *relative* fits of **nested** models. ```{r anova} anova(house.null, house.glm0, test = "Chisq") ``` ## Visualising model fit The baseline model is shown in the mosaic plot below. Note that this is applied not to the `housing` data, but rather to the `house.glm0` object (of class `glm`) resulting to a call to `vcdExtra::mosaic.glm()`. With four variables in the mosaic, labeling of the variable names and factor levels is a bit tricky, because labels must appear on all four sides of the plot. The `labeling_args` argument can be used to set more informative variable names and abbreviate factor levels where necessary. ```{r} #| label= mosaic-glm0a, #| warning = TRUE # labeling_args for mosaic() largs <- list(set_varnames = c( Infl="Influence on management", Cont="Contact among residents", Type="Type of dwelling", Sat="Satisfaction"), abbreviate=c(Type=3)) mosaic(house.glm0, labeling_args=largs, main='Baseline model: [ITC][Sat]') ``` In this plot we can see largish `r colorize("positive residuals", "blue")` in the blocks corresponding to (low satisfaction, low influence) and (high satisfaction, high influence) and clusters of largish `r colorize("negative residuals", "red")` in the opposite corners. By default, variables are used in the mosaic display in their order in the data table or frequency data.frame. The `r colorize("warning", "red")` reminds us that the order of conditioning used is `~Sat + Infl + Type + Cont`. ### Ordering the variables in the mosaic For `mosaic.glm()`, the conditioning order of variables in the mosaic can be set using the `formula` argument. Here, I rearrange the variables to put `Sat` as the last variable in the splitting / conditioning sequence. I also use `vcdExtra::modFit()` to add the LR $G^2$ fit statistic to the plot title. ```{r mosaic-glm0b} mosaic(house.glm0, formula = ~ Type + Infl + Cont + Sat, labeling_args=largs, main=paste('Baseline model: [ITC][Sat],', modFit(house.glm0)) ) ``` ## Adding association terms Clearly, satisfaction depends on one or more of the predictors, `Infl`, `Type` and `Cont` and possibly their interactions. As a first step it is useful to consider sequentially adding the association terms `Infl:Sat`, `Type:Sat`, `Cont:Sat` one at a time. This analysis is carried out using `MASS::addterm()`. ```{r addterm} MASS::addterm(house.glm0, ~ . + Sat:(Infl + Type + Cont), test = "Chisq") ``` Based on this, it is useful to consider a "main-effects" model for satisfaction, adding all three two-way terms involving satisfaction. The `update()` method provides an easy way to add (or subtract) terms from a fitted model object. In the model formula, `.` stands for whatever was on the left side (`Freq`) or on the right side (`Sat + Infl*Type*Cont`) of the model (`house.glm0`) that is being updated. ```{r house-glm1} house.glm1 <- update(house.glm0, . ~ . + Sat*(Infl + Type + Cont)) ``` For comparison, we note that the same model can be fit using the iterative proportional scaling algorithm of `MASS::loglm()`. ```{r house-loglm1} (house.loglm1 <- MASS::loglm(Freq ~ Infl * Type * Cont + Sat*(Infl + Type + Cont), data = housing)) ``` ## Did the model get better? As before, `anova()` tests the added contribution of each more complex model over the one before. The residual deviance $G^2$ has been reduced from $G^2 (46) = 217.46$ for the baseline model `house.glm0` to $G^2 (34) = 38.66$ for the revised model `house.glm1`. The difference, $G^2(M1 | M0) = G^2 (12) = 178.79$ tests the collective additional fit provided by the two-way association of satisfaction with the predictors. ```{r} anova(house.glm0, house.glm1, test="Chisq") ``` ## Visualize model `glm1` The model `house.glm1` fits reasonably well, `r modFit(house.glm1)`, so most residuals are small. In the mosaic below, I use `gp=shading_Friendly` to shade the tiles so that positive and negative residuals are distinguished by color, and they are filled when the absolute value of the residual is outside $\pm 2, 4$. ```{r mosaic-glm1} mosaic(house.glm1, labeling_args=largs, main=paste('Model [IS][TS][CS],', modFit(house.glm1) ), gp=shading_Friendly) ``` One cell is highlighted here: The combination of medium influence, low contact and tower type, is more likely to give low satisfaction than the model predicts. Is this just an outlier, or is there something that can be interpreted and perhaps improve the model fit? It is hard tell, but the virtues of mosaic displays are that they help to: * diagnose overall patterns of associations, * spot unusual cells in relation to lack of fit of a given model. ## Can we drop any terms? When we add terms using `MASS::addterm()`, they are added sequentially. It might be the case that once some term is added, a previously added term is no longer important. Running `MASS::dropterm()` on the `housel.glm1` model checks for this. ```{r dropterm} MASS::dropterm(house.glm1, test = "Chisq") ``` Note that the three-way term `Infl:Type:Cont` is not significant. However, with `Sat` as the response, the associations of all predictors must be included in the model. ## What about two-way interactions? The model so far says that each of influence, type and control have separate, additive effects on the level of satisfaction, what I called a "main-effects" model. It might be the case that some of the predictors have *interaction* effects, e.g., that the effect of influence on satisfaction might vary with the type of dwelling or the level of control. An easy way to test for these is to update the main-effects model, adding all possible two-way interactions for `Sat`, one at a time, with `addterm()`. ```{r addterm1} MASS::addterm(house.glm1, ~. + Sat:(Infl + Type + Cont)^2, test = "Chisq") ``` The result shows that adding the term `Infl:Type:Sat` reduces the deviance $G^2$ from 38.66 to 16.11. The difference, $G^2(M1 + ITS | M1) = G^2 (12) = 22.55$ reflects a substantial improvement. The remaining two-way interaction terms reduce the deviance by smaller and non-significant amounts, relative to `house.glm1`. Model fitting should be guided by substance, not just statistical machinery. Nonetheless, it seems arguably sensible to add one two-way term to the model, giving `house.glm2`. ```{r} house.glm2 <- update(house.glm1, . ~ . + Sat:Infl:Type) ``` ## Model parsimony: AIC & BIC Adding more association terms to a model will always improve it. The question is, whether that is "worth it"? "Worth it" concerns the trade-off between model fit and parsimony. Sometimes we might prefer a model with fewer parameters to one that has a slightly better fit, but requires more model terms and parameters. The AIC and BIC statistics are designed to adjust our assessment of model fit by penalizing it for using more parameters. Equivalently, they deduct from the likelihood ratio $G^2$ a term proportional to the residual $\text{df}$ of the model. In any case -- **smaller is better** for both AIC and BIC. $$AIC = G^2 - 2 \: \text{df}$$ $$BIC = G^2 - \log(n) \: \text{df}$$ These measures are provided by `AIC()`, `BIC()`, and can be used to compare models using `vcdExtra::LRstats()`. ```{r lrstats} LRstats(house.glm0, house.glm1, house.glm2) ``` By these metrics, model `house.glm1` is best on both AIC and BIC. The increased goodness-of-fit (smaller $G^2$) of model `house.glm2` is not worth the extra cost of parameters in the `house.glm2` model. <!-- ## Effect plots --> <!-- ```{r} --> <!-- house.eff <-allEffects(house.glm1) --> <!-- ``` -->
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/demo-housing.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut03-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ## ---- loglm-hec1-------------------------------------------------------------- library(MASS) ## Independence model of hair and eye color and sex. hec.1 <- loglm(~Hair+Eye+Sex, data=HairEyeColor) hec.1 ## ---- loglm-hec2-------------------------------------------------------------- ## Conditional independence hec.2 <- loglm(~(Hair + Eye) * Sex, data=HairEyeColor) hec.2 ## ---- loglm-hec3-------------------------------------------------------------- ## Joint independence model. hec.3 <- loglm(~Hair*Eye + Sex, data=HairEyeColor) hec.3 ## ---- loglm-anova------------------------------------------------------------- anova(hec.1, hec.2, hec.3) ## ---- mental1----------------------------------------------------------------- data(Mental, package = "vcdExtra") str(Mental) xtabs(Freq ~ mental + ses, data=Mental) # display the frequency table ## ---- mental2----------------------------------------------------------------- indep <- glm(Freq ~ mental + ses, family = poisson, data = Mental) # independence model ## ---- mental3----------------------------------------------------------------- # Use integer scores for rows/cols Cscore <- as.numeric(Mental$ses) Rscore <- as.numeric(Mental$mental) ## ---- mental4----------------------------------------------------------------- # column effects model (ses) coleff <- glm(Freq ~ mental + ses + Rscore:ses, family = poisson, data = Mental) # row effects model (mental) roweff <- glm(Freq ~ mental + ses + mental:Cscore, family = poisson, data = Mental) # linear x linear association linlin <- glm(Freq ~ mental + ses + Rscore:Cscore, family = poisson, data = Mental) ## ---- mental4a---------------------------------------------------------------- # compare models using AIC, BIC, etc vcdExtra::LRstats(glmlist(indep, roweff, coleff, linlin)) ## ---- mental5----------------------------------------------------------------- anova(indep, linlin, coleff, test="Chisq") anova(indep, linlin, roweff, test="Chisq") ## ---- mental6----------------------------------------------------------------- CMHtest(xtabs(Freq~ses+mental, data=Mental)) ## ---- mental7----------------------------------------------------------------- RC1 <- gnm(Freq ~ mental + ses + Mult(mental,ses), data=Mental, family=poisson, verbose=FALSE) RC2 <- gnm(Freq ~ mental+ses + instances(Mult(mental,ses),2), data=Mental, family=poisson, verbose=FALSE) anova(indep, RC1, RC2, test="Chisq")
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/loglinear.R
--- title: "Loglinear Models" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Loglinear Models} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut03-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ``` You can use the `loglm()` function in the `MASS` package to fit log-linear models. Equivalent models can also be fit (from a different perspective) as generalized linear models with the `glm()` function using the `family='poisson'` argument, and the `gnm` package provides a wider range of generalized *nonlinear* models, particularly for testing structured associations. The visualization methods for these models were originally developed for models fit using `loglm()`, so this approach is emphasized here. Some extensions of these methods for models fit using `glm()` and `gnm()` are contained in the `vcdExtra` package and illustrated in @ref(sec:glm). Assume we have a 3-way contingency table based on variables A, B, and C. The possible different forms of loglinear models for a 3-way table are shown in the table below. \@(tab:loglin-3way) The **Model formula** column shows how to express each model for `loglm()` in R. ^[For `glm()`, or `gnm()`, with the data in the form of a frequency data.frame, the same model is specified in the form `glm(Freq` $\sim$ `..., family="poisson")`, where `Freq` is the name of the cell frequency variable and `...` specifies the *Model formula*.] In the **Interpretation** column, the symbol "$\perp$" is to be read as "is independent of," and "$\;|\;$" means "conditional on," or "adjusting for," or just "given". | **Model** | **Model formula** | **Symbol** | **Interpretation** | |:-------------------------|:-------------------|:---------------|:-----------------------| | Mutual independence | `~A + B + C` | $[A][B][C]$ | $A \perp B \perp C$ | | Joint independence | `~A*B + C` | $[AB][C]$ | $(A \: B) \perp C$ | | Conditional independence | `~(A+B)*C` | $[AC][BC]$ | $(A \perp B) \;|\; C$ | | All two-way associations | `~A*B + A*C + B*C` | $[AB][AC][BC]$ | homogeneous association| | Saturated model | `~A*B*C` | $[ABC]$ | 3-way association | For example, the formula `~A + B + C` specifies the model of *mutual independence* with no associations among the three factors. In standard notation for the expected frequencies $m_{ijk}$, this corresponds to $$ \log ( m_{ijk} ) = \mu + \lambda_i^A + \lambda_j^B + \lambda_k^C \equiv A + B + C $$ The parameters $\lambda_i^A , \lambda_j^B$ and $\lambda_k^C$ pertain to the differences among the one-way marginal frequencies for the factors A, B and C. Similarly, the model of *joint independence*, $(A \: B) \perp C$, allows an association between A and B, but specifies that C is independent of both of these and their combinations, $$ \log ( m_{ijk} ) = \mu + \lambda_i^A + \lambda_j^B + \lambda_k^C + \lambda_{ij}^{AB} \equiv A * B + C $$ where the parameters $\lambda_{ij}^{AB}$ pertain to the overall association between A and B (collapsing over C). In the literature or text books, you will often find these models expressed in shorthand symbolic notation, using brackets, `[ ]` to enclose the *high-order terms* in the model. Thus, the joint independence model can be denoted `[AB][C]`, as shown in the **Symbol** column in the table. \@(tab:loglin-3way). Models of *conditional independence* allow (and fit) two of the three possible two-way associations. There are three such models, depending on which variable is conditioned upon. For a given conditional independence model, e.g., `[AB][AC]`, the given variable is the one common to all terms, so this example has the interpretation $(B \perp C) \;|\; A$. ## Fitting with `loglm()` {#sec:loglm} For example, we can fit the model of mutual independence among hair color, eye color and sex in `HairEyeColor` as ```{r, loglm-hec1} library(MASS) ## Independence model of hair and eye color and sex. hec.1 <- loglm(~Hair+Eye+Sex, data=HairEyeColor) hec.1 ``` Similarly, the models of conditional independence and joint independence are specified as ```{r, loglm-hec2} ## Conditional independence hec.2 <- loglm(~(Hair + Eye) * Sex, data=HairEyeColor) hec.2 ``` ```{r, loglm-hec3} ## Joint independence model. hec.3 <- loglm(~Hair*Eye + Sex, data=HairEyeColor) hec.3 ``` Note that printing the model gives a brief summary of the goodness of fit. A set of models can be compared using the `anova()` function. ```{r, loglm-anova} anova(hec.1, hec.2, hec.3) ``` ## Fitting with `glm()` and `gnm()` {#sec:glm} The `glm()` approach, and extensions of this in the `gnm` package allows a much wider class of models for frequency data to be fit than can be handled by `loglm()`. Of particular importance are models for ordinal factors and for square tables, where we can test more structured hypotheses about the patterns of association than are provided in the tests of general association under `loglm()`. These are similar in spirit to the non-parametric CMH tests described in \@ref(sec:CMH). ***Example***: The data `Mental` in the `vcdExtra` package gives a two-way table in frequency form classifying young people by their mental health status and parents' socioeconomic status (SES), where both of these variables are ordered factors. ```{r, mental1} data(Mental, package = "vcdExtra") str(Mental) xtabs(Freq ~ mental + ses, data=Mental) # display the frequency table ``` Simple ways of handling ordinal variables involve assigning scores to the table categories, and the simplest cases are to use integer scores, either for the row variable (``column effects'' model), the column variable (``row effects'' model), or both (``uniform association'' model). ```{r, mental2} indep <- glm(Freq ~ mental + ses, family = poisson, data = Mental) # independence model ``` To fit more parsimonious models than general association, we can define numeric scores for the row and column categories ```{r, mental3} # Use integer scores for rows/cols Cscore <- as.numeric(Mental$ses) Rscore <- as.numeric(Mental$mental) ``` Then, the row effects model, the column effects model, and the uniform association model can be fit as follows. The essential idea is to replace a factor variable with its numeric equivalent in the model formula for the association term. ```{r, mental4} # column effects model (ses) coleff <- glm(Freq ~ mental + ses + Rscore:ses, family = poisson, data = Mental) # row effects model (mental) roweff <- glm(Freq ~ mental + ses + mental:Cscore, family = poisson, data = Mental) # linear x linear association linlin <- glm(Freq ~ mental + ses + Rscore:Cscore, family = poisson, data = Mental) ``` The `LRstats()` function in `vcdExtra` provides a nice, compact summary of the fit statistics for a set of models, collected into a *glmlist* object. Smaller is better for AIC and BIC. ```{r, mental4a} # compare models using AIC, BIC, etc vcdExtra::LRstats(glmlist(indep, roweff, coleff, linlin)) ``` For specific model comparisons, we can also carry out tests of *nested* models with `anova()` when those models are listed from smallest to largest. Here, there are two separate paths from the most restrictive (independence) model through the model of uniform association, to those that allow only one of row effects or column effects. ```{r, mental5} anova(indep, linlin, coleff, test="Chisq") anova(indep, linlin, roweff, test="Chisq") ``` The model of linear by linear association seems best on all accounts. For comparison, one might try the CMH tests on these data: ```{r, mental6} CMHtest(xtabs(Freq~ses+mental, data=Mental)) ``` ## Non-linear terms The strength of the `gnm` package is that it handles a wide variety of models that handle non-linear terms, where the parameters enter the model beyond a simple linear function. The simplest example is the Goodman RC(1) model [@Goodman:79], which allows a multiplicative term to account for the association of the table variables. In the notation of generalized linear models with a log link, this can be expressed as $$ \log \mu_{ij} = \alpha_i + \beta_j + \gamma_{i} \delta_{j} ,$$ where the row-multiplicative effect parameters $\gamma_i$ and corresponding column parameters $\delta_j$ are estimated from the data.% ^[This is similar in spirit to a correspondence analysis with a single dimension, but as a statistical model.] Similarly, the RC(2) model adds two multiplicative terms to the independence model, $$ \log \mu_{ij} = \alpha_i + \beta_j + \gamma_{i1} \delta_{j1} + \gamma_{i2} \delta_{j2} . $$ In the `gnm` package, these models may be fit using the `Mult()` to specify the multiplicative term, and `instances()` to specify several such terms. ***Example***: For the `Mental` data, we fit the RC(1) and RC(2) models, and compare these with the independence model. ```{r, mental7} RC1 <- gnm(Freq ~ mental + ses + Mult(mental,ses), data=Mental, family=poisson, verbose=FALSE) RC2 <- gnm(Freq ~ mental+ses + instances(Mult(mental,ses),2), data=Mental, family=poisson, verbose=FALSE) anova(indep, RC1, RC2, test="Chisq") ``` ## References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/loglinear.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/mobility-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # colorize text colorize <- function(x, color) { if (knitr::is_latex_output()) { sprintf("\\textcolor{%s}{%s}", color, x) } else if (knitr::is_html_output()) { sprintf("<span style='color: %s;'>%s</span>", color, x) } else x } ## ----hauser-data-------------------------------------------------------------- data("Hauser79", package="vcdExtra") str(Hauser79) (Hauser_tab <- xtabs(Freq ~ Father + Son, data=Hauser79)) ## ----load--------------------------------------------------------------------- library(vcdExtra) library(gnm) library(dplyr) ## ----mosaicplot--------------------------------------------------------------- plot(Hauser_tab, shade=TRUE) ## ----mosaic1------------------------------------------------------------------ labels <- list(set_varnames = c(Father="Father's occupation", Son="Son's occupation")) mosaic(Freq ~ Father + Son, data=Hauser79, labeling_args = labels, shade=TRUE, legend = FALSE) ## ----indep-------------------------------------------------------------------- hauser.indep <- glm(Freq ~ Father + Son, data=Hauser79, family=poisson) # the same mosaic, using the fitted model mosaic(hauser.indep, formula = ~ Father + Son, labeling_args = labels, legend = FALSE, main="Independence model") ## ----Diag--------------------------------------------------------------------- # with symbols with(Hauser79, Diag(Father, Son)) |> matrix(nrow=5) ## ----quasi-------------------------------------------------------------------- hauser.quasi <- update(hauser.indep, ~ . + Diag(Father, Son)) mosaic(hauser.quasi, ~ Father+Son, labeling_args = labels, legend = FALSE, main="Quasi-independence model") ## ----symm--------------------------------------------------------------------- with(Hauser79, Symm(Father, Son)) |> matrix(nrow=5) ## ----qsymm-------------------------------------------------------------------- hauser.qsymm <- update(hauser.indep, ~ . + Diag(Father,Son) + Symm(Father,Son)) ## ----anova1------------------------------------------------------------------- anova(hauser.indep, hauser.quasi, hauser.qsymm, test="Chisq") LRstats(hauser.indep, hauser.quasi, hauser.qsymm) ## ----qsymm-mosaic------------------------------------------------------------- mosaic(hauser.qsymm, ~ Father+Son, labeling_args = labels, labeling = labeling_residuals, residuals_type ="rstandard", legend = FALSE, main="Quasi-symmetry model") ## ----topo-levels-------------------------------------------------------------- # Levels for Hauser 5-level model levels <- matrix(c( 2, 4, 5, 5, 5, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 4, 1), nrow = 5, ncol = 5, byrow=TRUE) ## ----topo-mosaic-------------------------------------------------------------- hauser.topo <- update(hauser.indep, ~ . + Topo(Father, Son, spec=levels)) mosaic(hauser.topo, ~Father+Son, labeling_args = labels, labeling = labeling_residuals, residuals_type ="rstandard", legend = FALSE, main="Topological model") ## ----------------------------------------------------------------------------- LRstats(hauser.indep, hauser.quasi, hauser.qsymm, hauser.topo, sortby = "AIC") ## ----scores------------------------------------------------------------------- Sscore <- as.numeric(Hauser79$Son) Fscore <- as.numeric(Hauser79$Father) Hauser79 |> cbind(Fscore, Fscore) |> head() ## ----hauser-UAdiag------------------------------------------------------------ hauser.UAdiag <- update(hauser.indep, . ~ . + Fscore : Sscore + Diag(Father, Son)) LRstats(hauser.UAdiag) ## ----------------------------------------------------------------------------- coef(hauser.UAdiag)[["Fscore:Sscore"]] ## ----UAdiag-mosaic------------------------------------------------------------ mosaic(hauser.UAdiag, ~ Father+Son, labeling_args = labels, labeling = labeling_residuals, residuals_type ="rstandard", legend = FALSE, main="Uniform association + Diag()")
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/mobility.R
--- title: "Mobility tables" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib", "vignettes.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Mobility tables} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/mobility-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # colorize text colorize <- function(x, color) { if (knitr::is_latex_output()) { sprintf("\\textcolor{%s}{%s}", color, x) } else if (knitr::is_html_output()) { sprintf("<span style='color: %s;'>%s</span>", color, x) } else x } ``` ## Social mobility Social mobility is an important concept in sociology, and its' study has led to a wide range of developments in categorical data analysis in what are often called _mobility tables_. The idea is to study the movement of individuals, families, households or other categories of people within or between social strata in a society, across time or space. This refers to a change in social status relative to one's current social location within a given society. Using survey data, the most frequent examples relate to changes in income or wealth, but most often this is studied via classification in occupational categories ("professional, "managerial", "skilled manual", ...). Most often this is studied _intergenerationaly_ using the occupational categories of fathers and sons. Mobility tables are nearly always _square_ tables, with the same categories for the row and column variables. As such, they nearly always exhibit positive associations along the diagonal cells. What is of interest are specialized models, intermediate between the null model of independence and the saturated model. ### Models These models include important special cases: - **quasi-independence**: Ignoring diagonal cells, are the row and column variables independent? - **symmetry**: Are associations above the diagonal equal to the corresponding ones below the diagonal? - **row effects, col effects, linear x linear**: Typically, the factors in such tables are ordinal. To what extent can the models be simplified by assigning integer scores to the row, column categories or both? - **multiplicative RC**: RC models attempt to estimate the scores for the row and column categories. - **topographical models**: It is possible that the associations among occupational categories exhibit consistent patterns according to their nature. These models allow specifying a theoretically interesting pattern. - **crossings models**: assert that there are different difficulty parameters for crossing from category to the next and associations between categories decrease with their separation. While standard loglinear models can be fit using `MASS::loglm`, these models require use of ``stats::glm()` or `gnm::gnm()`, as I illustrate below. ## Hauser data This vignette uses the `vcdExtra::Hauser79` dataset, a cross-classification of 19,912 individuals by father's occupation and son's first occupation for U.S. men aged 20-64 in 1973. The data comes from @Hauser:79 and has been also analysed by @PowersXie:2008. The discussion draws on @FriendlyMeyer:2016:DDAR, Ch. 10. ```{r hauser-data} data("Hauser79", package="vcdExtra") str(Hauser79) (Hauser_tab <- xtabs(Freq ~ Father + Son, data=Hauser79)) ``` As can be seen, `Hauser79` is a data.frame in frequency form. The factor levels in this table are a coarse grouping of occupational categories, so: - `UpNM` = professional and kindred workers, managers and officials, and non-retail sales workers; - `LoNM` = proprietors, clerical and kindred workers, and retail sales workers; - `UpM` = craftsmen, foremen, and kindred workers; - `LoM` = service workers, operatives and kindred workers, and laborers (except farm); - `Farm` = farmers and farm managers, farm laborers, and foremen. ### Load packages ```{r load} library(vcdExtra) library(gnm) library(dplyr) ``` ### Mosaic plots `Hauser_tab` is a `table` object, and the simplest plot for the frequencies is the default `plot()` method, giving a `graphics::mosaicplot()`. ```{r mosaicplot} plot(Hauser_tab, shade=TRUE) ``` The frequencies are first split according to father's occupational category (the first table dimension) and then by sons' occupation. The most common category for fathers is lower manual, followed by farm. `mosaicplot()`, using `shade=TRUE` colors the tiles according to the sign and magnitude of the residuals from an independence model: shades of `r colorize("positive", "blue")` for positive residuals and `r colorize("negative", "red")` red for negative residuals. `vcd::mosaic()` gives a similar display, but is much more flexible in the labeling of the row and column variable, labels for the categories, and the scheme used for shading the tiles. Here, I simply assign longer labels for the row and column variables, using the `labeling_args` argument to `mosaic()`. ```{r mosaic1} labels <- list(set_varnames = c(Father="Father's occupation", Son="Son's occupation")) mosaic(Freq ~ Father + Son, data=Hauser79, labeling_args = labels, shade=TRUE, legend = FALSE) ``` ### Fitting and graphing models The call to `vcd::mosaic()` above takes the `Hauser79` dataset as input. Internally, it fits the model of independence and displays the result, but for more complex tables, control of the fitted model is limited. Unlike `mosaicplot()` and even the [`ggmosaic`]( https://CRAN.R-project.org/package=ggmosaic) package, `vcdExtra::mosaic.glm()` is a `mosaic` **method** for `glm` objects. This means you can fit any model, and supply the model object to `mosaic()`. (Note that in `mosaic()`, the `formula` argument determines the order of splitting in the mosaic, not a loglinear formula.) ```{r indep} hauser.indep <- glm(Freq ~ Father + Son, data=Hauser79, family=poisson) # the same mosaic, using the fitted model mosaic(hauser.indep, formula = ~ Father + Son, labeling_args = labels, legend = FALSE, main="Independence model") ``` ## Quasi-independence Among the most important advances from the social mobility literature is the idea that associations between row and column variables in square tables can be explored in greater depth if we ignore the obvious association in the diagonal cells. The result is a model of _quasi-independence_, asserting that fathers' and sons' occupations are independent, ignoring the diagonal cells. For a two-way table, quasi-independence can be expressed as $$ \pi_{ij} = \pi_{i+} \pi_{+j} \quad\quad \mbox{for } i\ne j $$ or in loglinear form as: $$ \log m_{ij} = \mu + \lambda_i^A + \lambda_j^B + \delta_i I(i=j) \quad . $$ This model effectively adds one parameter, $\delta_i$, for each main diagonal cell and fits those frequencies perfectly. In the [`gnm`]( https://CRAN.R-project.org/package=gnm) package, `gnm::Diag()` creates the appropriate term in the model formula, using a symbol in the diagonal cells and "." otherwise. ```{r Diag} # with symbols with(Hauser79, Diag(Father, Son)) |> matrix(nrow=5) ``` We proceed to fit and plot the quasi-independence model by updating the independence model, adding the term `Diag(Father, Son)`. ```{r quasi} hauser.quasi <- update(hauser.indep, ~ . + Diag(Father, Son)) mosaic(hauser.quasi, ~ Father+Son, labeling_args = labels, legend = FALSE, main="Quasi-independence model") ``` Note that the pattern of residuals shows a systematic pattern of `r colorize("positive", "blue")` and `r colorize("negative", "red")` residuals above and below the diagonal tiles. We turn to this next. ### Symmetry and quasi-symmetry Another advance from the social mobility literature was the idea of how to test for _differences_ in occupational categories between fathers and sons. The null hypothesis of no systematic differences can be formulated as a test of **symmetry** in the table, $$ \pi_{ij} = \pi_{ji} \quad\quad \mbox{for } i\ne j \quad , $$ which asserts that sons are as likely to move from their father's occupation $i$ to another category $j$ as they were to move in the reverse direction, $j$ to $i$. An alternative, "Upward mobility", i.e., that sons who did not stay in their father's occupational category moved to a higher category on average would mean that $$ \pi_{ij} < \pi_{ji} \quad\quad \mbox{for } i\ne j $$ Yet this model is overly strong, because it also asserts **marginal homogeneity**, that the marginal probabilities of row and column values are equal, $\pi_{i+} = \pi_{+i}$ for all $i$. Consequently, this hypothesis is most often tested as a model for **quasi-symmetry**, that also ignores the diagonal cells. Symmetry is modeled by the function `gnm::Symm()`. It returns a factor with the same labels for positions above and below the diagonal. ```{r symm} with(Hauser79, Symm(Father, Son)) |> matrix(nrow=5) ``` To fit the model of quasi-symmetry, add both `Diag()` and `Symm()` to the model of independence. ```{r qsymm} hauser.qsymm <- update(hauser.indep, ~ . + Diag(Father,Son) + Symm(Father,Son)) ``` To compare the models so far, we can use `anova()` or `vcdExtra::LRstats(): ```{r anova1} anova(hauser.indep, hauser.quasi, hauser.qsymm, test="Chisq") LRstats(hauser.indep, hauser.quasi, hauser.qsymm) ``` This `hauser.qsymm` model represents a huge improvement in goodness of fit. With such a large sample size, it might be considered an acceptable fit. But, this model of quasi-symmetry still shows some residual lack of fit. To visualize this in the mosaic, we can label the cells with their standardized residuals. ```{r qsymm-mosaic} mosaic(hauser.qsymm, ~ Father+Son, labeling_args = labels, labeling = labeling_residuals, residuals_type ="rstandard", legend = FALSE, main="Quasi-symmetry model") ``` The cells with the largest lack of symmetry (using standardized residuals) are those for the upper and lower non-manual occupations, where the son of an upper manual worker is less likely to move to lower non-manual work than the reverse. ### Topological models It is also possible that there are more subtle patterns of association one might want to model, with specific parameters for particular combinations of the occupational categories (beyond the idea of symmetry). @Hauser:79 developed this idea in what are now called **topological** models or **levels** models, where an arbitrary pattern of associations can be specified, implemented in `gnm::Topo()`. ```{r topo-levels} # Levels for Hauser 5-level model levels <- matrix(c( 2, 4, 5, 5, 5, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 4, 1), nrow = 5, ncol = 5, byrow=TRUE) ``` ```{r topo-mosaic} hauser.topo <- update(hauser.indep, ~ . + Topo(Father, Son, spec=levels)) mosaic(hauser.topo, ~Father+Son, labeling_args = labels, labeling = labeling_residuals, residuals_type ="rstandard", legend = FALSE, main="Topological model") ``` Comparing models, we can see that the model of quasi-symmetry is the best so far, using AIC as the measure: ```{r} LRstats(hauser.indep, hauser.quasi, hauser.qsymm, hauser.topo, sortby = "AIC") ``` ## Ordinal tables Because the factors in mobility tables are ordered, another path to simplifying the saturated model is to consider assigning numerical scores (typically consecutive integers) to the categories. When both variables are assigned scores, this gives the **linear-by-linear model**, $$ \log ( m_{ij} ) = \mu + \lambda_i^A + \lambda_j^B + \gamma \: a_i b_j \quad , $$ where $a_i$ and $b_j$ are the row and column numeric scores. This model is also called the model of **uniform association** [@Goodman:79] because, for integer scores, $a_i=i$, $b_j=j$, this model has only one extra parameter, $\gamma$, which is the common odds local ratio. The independence model is the special case, $\gamma=0$. In contrast, the saturated model, allowing general association $\lambda_{ij}^{AB}$, uses $(I-1)(J-1)$ additional parameters. For square tables, like mobility tables, this model can be amended to include a diagonal term, `Diag()` ```{r scores} Sscore <- as.numeric(Hauser79$Son) Fscore <- as.numeric(Hauser79$Father) Hauser79 |> cbind(Fscore, Fscore) |> head() ``` To fit this model, I use `Fscore * Sscore` for the linear x linear association and add `Diag(Father, Son)` to fit the diagonal cells exactly. ```{r hauser-UAdiag} hauser.UAdiag <- update(hauser.indep, . ~ . + Fscore : Sscore + Diag(Father, Son)) LRstats(hauser.UAdiag) ``` In this model, the estimated common local log odds ratio---the coefficient $\gamma$ for the linear-by-linear term `Fscore:Sscore`, is given by: ```{r} coef(hauser.UAdiag)[["Fscore:Sscore"]] ``` For comparisons not involving the diagonal cells, each step down the scale of occupational categories for the father multiplies the odds that the son will also be in one lower category by $\exp (0.158) = 1.172$, an increase of 17%. But this model does not seem to be any improvement over quasi-symmetry. From the pattern of residuals in the mosaic, we see a number of large residuals of various signs in the lower triangular, where the son's occupation is of a higher level than that of the father. ```{r UAdiag-mosaic} mosaic(hauser.UAdiag, ~ Father+Son, labeling_args = labels, labeling = labeling_residuals, residuals_type ="rstandard", legend = FALSE, main="Uniform association + Diag()") ``` ## Model comparison plots Finally, for comparing a largish collection of models, a model comparison plot can show the trade-off between goodness-of-fit and parsimony by plotting measures like $G^2/df$, AIC, or BIC against degrees of freedom. The plot below, including quite a few more models, uses a log scale for BIC to emphasize differences among better fitting models. (The code for this plot is shown on p. 399 of @FriendlyMeyer:2016:DDAR). ![](fig/hauser-model-plot.png){width=80%} ## References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/mobility.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut04-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Load packages set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) library(seriation) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ## ----------------------------------------------------------------------------- data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) mosaic(art, gp = shading_max, split_vertical = TRUE, main="Arthritis: [Treatment] [Improved]") ## ---- art1-------------------------------------------------------------------- summary(art) ## ----------------------------------------------------------------------------- mosaic(art, gp = shading_Friendly, split_vertical = TRUE, main="Arthritis: gp = shading_Friendly") ## ----glass-------------------------------------------------------------------- data(Glass, package="vcdExtra") (glass.tab <- xtabs(Freq ~ father + son, data=Glass)) ## ----glass-mosaic1------------------------------------------------------------ largs <- list(set_varnames=list(father="Father's Occupation", son="Son's Occupation"), abbreviate=10) gargs <- list(interpolate=c(1,2,4,8)) mosaic(glass.tab, shade=TRUE, labeling_args=largs, gp_args=gargs, main="Alphabetic order", legend=FALSE, rot_labels=c(20,90,0,70)) ## ----glass-order-------------------------------------------------------------- # reorder by status ord <- c(2, 1, 4, 3, 5) row.names(glass.tab)[ord] ## ----glass-mosaic2------------------------------------------------------------ mosaic(glass.tab[ord, ord], shade=TRUE, labeling_args=largs, gp_args=gargs, main="Effect order", legend=FALSE, rot_labels=c(20,90,0,70)) ## ----glass-ord---------------------------------------------------------------- Glass.ord <- Glass Glass.ord$father <- ordered(Glass.ord$father, levels=levels(Glass$father)[ord]) Glass.ord$son <- ordered(Glass.ord$son, levels=levels(Glass$son)[ord]) str(Glass.ord) ## ----diag--------------------------------------------------------------------- rowfac <- gl(4, 4, 16) colfac <- gl(4, 1, 16) diag4by4 <- Diag(rowfac, colfac) matrix(Diag(rowfac, colfac, binary = FALSE), 4, 4) ## ----symm--------------------------------------------------------------------- symm4by4 <- Symm(rowfac, colfac) matrix(symm4by4, 4, 4) ## ----glass-models------------------------------------------------------------- library(gnm) glass.indep <- glm(Freq ~ father + son, data = Glass.ord, family=poisson) glass.quasi <- glm(Freq ~ father + son + Diag(father, son), data = Glass.ord, family=poisson) glass.symm <- glm(Freq ~ Symm(father, son), data = Glass.ord, family=poisson) glass.qsymm <- glm(Freq ~ father + son + Symm(father, son), data = Glass.ord, family=poisson) ## ----glass-quasi-------------------------------------------------------------- mosaic(glass.quasi, residuals_type="rstandard", shade=TRUE, labeling_args=largs, gp_args=gargs, main="Quasi-Independence", legend=FALSE, rot_labels=c(20,90,0,70) ) ## ----glass-anova-------------------------------------------------------------- # model comparisons: for *nested* models anova(glass.indep, glass.quasi, glass.qsymm, test="Chisq") ## ----glass-lrstats------------------------------------------------------------ models <- glmlist(glass.indep, glass.quasi, glass.symm, glass.qsymm) LRstats(models) ## ----glass-qsymm-------------------------------------------------------------- mosaic(glass.qsymm, residuals_type="rstandard", shade=TRUE, labeling_args=largs, gp_args=gargs, main = paste("Quasi-Symmetry", modFit(glass.qsymm)), legend=FALSE, rot_labels=c(20,90,0,70) ) ## ----housetasks--------------------------------------------------------------- data("HouseTasks", package = "vcdExtra") HouseTasks ## ----housetasks-mos1---------------------------------------------------------- require(vcd) mosaic(HouseTasks, shade = TRUE, labeling = labeling_border(rot_labels = c(45,0, 0, 0), offset_label =c(.5,5,0, 0), varnames = c(FALSE, TRUE), just_labels=c("center","right"), tl_varnames = FALSE), legend = FALSE) ## ----housetasks-ca------------------------------------------------------------ require(ca) HT.ca <- ca(HouseTasks) summary(HT.ca, rows=FALSE, columns=FALSE) ## ----housetasks-ca-plot------------------------------------------------------- plot(HT.ca, lines = TRUE) ## ----housetasks-seriation----------------------------------------------------- require(seriation) order <- seriate(HouseTasks, method = "CA") # the permuted row and column labels rownames(HouseTasks)[order[[1]]] colnames(HouseTasks)[order[[2]]] ## ----housetasks-mos2---------------------------------------------------------- # do the permutation HT_perm <- permute(HouseTasks, order, margin=1) mosaic(HT_perm, shade = TRUE, labeling = labeling_border(rot_labels = c(45,0, 0, 0), offset_label =c(.5,5,0, 0), varnames = c(FALSE, TRUE), just_labels=c("center","right"), tl_varnames = FALSE), legend = FALSE)
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/mosaics.R
--- title: "Mosaic plots" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Mosaic plots} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut04-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Load packages set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) library(seriation) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ``` Mosaic plots provide an ideal method both for visualizing contingency tables and for visualizing the fit--- or more importantly--- **lack of fit** of a loglinear model. For a two-way table, `mosaic()`, by default, fits a model of independence, $[A][B]$ or `~A + B` as an R formula. The `vcdExtra` package extends this to models fit using `glm(..., family=poisson)`, which can include specialized models for ordered factors, or square tables that are intermediate between the saturated model, $[A B]$ = `A * B`, and the independence model $[A][B]$. For $n$-way tables, `vcd::mosaic()` can fit any loglinear model, and can also be used to plot a model fit with `MASS:loglm()`. The `vcdExtra` package extends this to models fit using `stats::glm()` and, by extension, to non-linear models fit using the [gnm package](https://cran.r-project.org/package=gnm). See @vcd:Friendly:1994, @vcd:Friendly:1999 for the statistical ideas behind these uses of mosaic displays in connection with loglinear models. Our book @FriendlyMeyer:2016:DDAR gives a detailed discussion of mosaic plots and many more examples. The essential ideas are to: * recursively sub-divide a unit square into rectangular "tiles" for the cells of the table, such that the area of each tile is proportional to the cell frequency. Tiles are split in a sequential order: + First according to the **marginal** proportions of a first variable, V1 + Next according to the **conditional** proportions of a 2nd variable, V2 | V1 + Next according to the **conditional** proportions of a 3rd variable, V3 | {V1, V2} + ... * For a given loglinear model, the tiles can then be shaded in various ways to reflect the residuals (lack of fit) for a given model. * The pattern of residuals can then be used to suggest a better model or understand *where* a given model fits or does not fit. `mosaic()` provides a wide range of options for the directions of splitting, the specification of shading, labeling, spacing, legend and many other details. It is actually implemented as a special case of a more general class of displays for $n$-way tables called `strucplot`, including sieve diagrams, association plots, double-decker plots as well as mosaic plots. For details, see `help(strucplot)` and the "See also" links therein, and also @vcd:Meyer+Zeileis+Hornik:2006b, which is available as an R vignette via `vignette("strucplot", package="vcd")`. ***Example***: A mosaic plot for the Arthritis treatment data fits the model of independence, `~ Treatment + Improved` and displays the association in the pattern of residual shading. The goal is to visualize the difference in the proportions of `Improved` for the two levels of `Treatment` : "Placebo" and "Treated". The plot below is produced with the following call to `mosaic()`. With the first split by `Treatment` and the shading used, it is easy to see that more people given the placebo experienced no improvement, while more people given the active treatment reported marked improvement. ```{r} #| Arthritis1, #| fig.height = 6, #| fig.width = 7, #| fig.cap = "Mosaic plot for the `Arthritis` data, using `shading_max`" data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) mosaic(art, gp = shading_max, split_vertical = TRUE, main="Arthritis: [Treatment] [Improved]") ``` `gp = shading_max` specifies that color in the plot signals a significant residual at a 90% or 99% significance level, with the more intense shade for 99%. Note that the residuals for the independence model were not large (as shown in the legend), yet the association between `Treatment` and `Improved` is highly significant. ```{r, art1} summary(art) ``` In contrast, one of the other shading schemes, from @vcd:Friendly:1994 (use: `gp = shading_Friendly`), uses fixed cutoffs of $\pm 2, \pm 4$, to shade cells which are *individually* significant at approximately $\alpha = 0.05$ and $\alpha = 0.001$ levels, respectively. The plot below uses `gp = shading_Friendly`. ```{r} #| Arthritis2, #| fig.height = 6, #| fig.width = 7, #| fig.cap = "Mosaic plot for the `Arthritis` data, using `shading_Friendly`" mosaic(art, gp = shading_Friendly, split_vertical = TRUE, main="Arthritis: gp = shading_Friendly") ``` ## Permuting variable levels Mosaic plots using tables or frequency data frames as input typically take the levels of the table variables in the order presented in the dataset. For character variables, this is often alphabetical order. That might be helpful for looking up a value, but is unhelpful for seeing and understanding the pattern of association. It is usually much better to order the levels of the row and column variables to help reveal the nature of their association. This is an example of **effect ordering for data display** [@FriendlyKwan:02:effect]. ***Example***: Data from @Glass:54 gave this 5 x 5 table on the occupations of 3500 British fathers and their sons, where the occupational categories are listed in alphabetic order. ```{r glass} data(Glass, package="vcdExtra") (glass.tab <- xtabs(Freq ~ father + son, data=Glass)) ``` The mosaic display shows very strong association, but aside from the diagonal cells, the pattern is unclear. Note the use of `set_varnames` to give more descriptive labels for the variables and abbreviate the occupational category labels. and `interpolate` to set the shading levels for the mosaic. ```{r glass-mosaic1} largs <- list(set_varnames=list(father="Father's Occupation", son="Son's Occupation"), abbreviate=10) gargs <- list(interpolate=c(1,2,4,8)) mosaic(glass.tab, shade=TRUE, labeling_args=largs, gp_args=gargs, main="Alphabetic order", legend=FALSE, rot_labels=c(20,90,0,70)) ``` The occupational categories differ in **status**, and can be reordered correctly as follows, from `Professional` down to `Unskilled`. ```{r glass-order} # reorder by status ord <- c(2, 1, 4, 3, 5) row.names(glass.tab)[ord] ``` The revised mosaic plot can be produced by indexing the rows and columns of the table using `ord`. ```{r glass-mosaic2} mosaic(glass.tab[ord, ord], shade=TRUE, labeling_args=largs, gp_args=gargs, main="Effect order", legend=FALSE, rot_labels=c(20,90,0,70)) ``` From this, and for the examples in the next section, it is useful to re-define `father` and `son` as **ordered** factors in the original `Glass` frequency data.frame. ```{r glass-ord} Glass.ord <- Glass Glass.ord$father <- ordered(Glass.ord$father, levels=levels(Glass$father)[ord]) Glass.ord$son <- ordered(Glass.ord$son, levels=levels(Glass$son)[ord]) str(Glass.ord) ``` ## Square tables For mobility tables such as this, where the rows and columns refer to the same occupational categories it comes as no surprise that there is a strong association in the diagonal cells: most often, sons remain in the same occupational categories as their fathers. However, the re-ordered mosaic display also reveals something subtler: when a son differs in occupation from the father, it is more likely that he will appear in a category one-step removed than more steps removed. The residuals seem to decrease with the number of steps from the diagonal. For such tables, specialized loglinear models provide interesting cases intermediate between the independence model, [A] [B], and the saturated model, [A B]. These can be fit using `glm()`, with the data in frequency form, ``` glm(Freq ~ A + B + assoc, data = ..., family = poisson) ``` where `assoc` is a special term to handle a restricted form of association, different from `A:B` which specifies the saturated model in this notation. * **Quasi-independence**: Asserts independence, but ignores the diagonal cells by fitting them exactly. The loglinear model is: $\log m_{ij} = \mu + \lambda^A_i + \lambda^B_j + \delta_i I(i = j)$, where $I()$ is the indicator function. * **Symmetry**: This model asserts that the joint distribution of the row and column variables is symmetric, that is $\pi_{ij} = \pi_{ji}$: A son is equally likely to move from their father's occupational category $i$ to another category, $j$, as the reverse, moving from $j$ to $i$. Symmetry is quite strong, because it also implies **marginal homogeneity**, that the marginal probabilities of the row and column variables are equal, $\pi{i+} = \sum_j \pi_{ij} = \sum_j \pi_{ji} = \pi_{+i}$ for all $i$. * **Quasi-symmetry**: This model uses the standard main-effect terms in the loglinear model, but asserts that the association parameters are symmetric, $\log m_{ij} = \mu + \lambda^A_i + \lambda^B_j + \lambda^{AB}_{ij}$, where $\lambda^{AB}_{ij} = \lambda^{AB}_{ji}$. The [gnm package](https://cran.r-project.org/package=gnm) provides a variety of these functions: `gnm::Diag()`, `gnm::Symm()` and `gnm::Topo()` for an interaction factor as specified by an array of levels, which may be arbitrarily structured. For example, the following generates a term for a diagonal factor in a $4 \times 4$ table. The diagonal values reflect parameters fitted for each diagonal cell. Off-diagonal values, "." are ignored. ```{r diag} rowfac <- gl(4, 4, 16) colfac <- gl(4, 1, 16) diag4by4 <- Diag(rowfac, colfac) matrix(Diag(rowfac, colfac, binary = FALSE), 4, 4) ``` `Symm()` constructs parameters for symmetric cells. The particular values don't matter. All that does matter is that the same value, e.g., `1:2` appears in both the (1,2) and (2,1) cells. ```{r symm} symm4by4 <- Symm(rowfac, colfac) matrix(symm4by4, 4, 4) ``` ***Example***: To illustrate, we fit the four models below, starting with the independence model `Freq ~ father + son` and then adding terms to reflect the restricted forms of association, e.g., `Diag(father, son)` for diagonal terms and `Symm(father, son)` for symmetry. ```{r glass-models} library(gnm) glass.indep <- glm(Freq ~ father + son, data = Glass.ord, family=poisson) glass.quasi <- glm(Freq ~ father + son + Diag(father, son), data = Glass.ord, family=poisson) glass.symm <- glm(Freq ~ Symm(father, son), data = Glass.ord, family=poisson) glass.qsymm <- glm(Freq ~ father + son + Symm(father, son), data = Glass.ord, family=poisson) ``` We can visualize these using the `vcdExtra::mosaic.glm()` method, which extends mosaic displays to handle fitted `glm` objects. *Technical note*: for models fitted using `glm()`, standardized residuals, `residuals_type="rstandard"` have better statistical properties than the default Pearson residuals in mosaic plots and analysis. ```{r glass-quasi} mosaic(glass.quasi, residuals_type="rstandard", shade=TRUE, labeling_args=largs, gp_args=gargs, main="Quasi-Independence", legend=FALSE, rot_labels=c(20,90,0,70) ) ``` Mosaic plots for the other models would give further visual assessment of these models, however we can also test differences among them. For nested models, `anova()` gives tests of how much better a more complex model is compared to the previous one. ```{r glass-anova} # model comparisons: for *nested* models anova(glass.indep, glass.quasi, glass.qsymm, test="Chisq") ``` Alternatively, `vcdExtra::LRstats()` gives model summaries for a collection of models, not necessarily nested, with AIC and BIC statistics reflecting model parsimony. ```{r glass-lrstats} models <- glmlist(glass.indep, glass.quasi, glass.symm, glass.qsymm) LRstats(models) ``` By all criteria, the model of quasi symmetry fits best. The residual deviance $G^2 is not significant. The mosaic is largely unshaded, indicating a good fit, but there are a few shaded cells that indicate the remaining positive and negative residuals. For comparative mosaic displays, it is sometimes useful to show the $G^2$ statistic in the main title, using `vcdExtra::modFit()` for this purpose. ```{r glass-qsymm} mosaic(glass.qsymm, residuals_type="rstandard", shade=TRUE, labeling_args=largs, gp_args=gargs, main = paste("Quasi-Symmetry", modFit(glass.qsymm)), legend=FALSE, rot_labels=c(20,90,0,70) ) ``` ## Correspondence analysis ordering When natural orders for row and column levels are not given a priori, we can find orderings that make more sense using correspondence analysis. The general ideas are that: * Correspondence analysis assigns scores to the row and column variables to best account for the association in 1, 2, ... dimensions * The first CA dimension accounts for largest proportion of the Pearson $\chi^2$ * Therefore, permuting the levels of the row and column variables by the CA Dim1 scores gives a more coherent mosaic plot, more clearly showing the nature of the association. * The [seriation package](https://cran.r-project.org/package=seriation) now has a method to order variables in frequency tables using CA. ***Example***: As an example, consider the `HouseTasks` dataset, a 13 x 4 table of frequencies of household tasks performed by couples, either by the `Husband`, `Wife`, `Alternating` or `Jointly`. You can see from the table that some tasks (Repairs) are done largely by the husband; some (laundry, main meal) are largely done by the wife, while others are done jointly or alternating between husband and wife. But the `Task` and `Who` levels are both in alphabetical order. ```{r housetasks} data("HouseTasks", package = "vcdExtra") HouseTasks ``` The naive mosaic plot for this dataset is shown below, splitting first by `Task` and then by `Who`. Due to the length of the factor labels, some features of `labeling` were used to make the display more readable. ```{r housetasks-mos1} require(vcd) mosaic(HouseTasks, shade = TRUE, labeling = labeling_border(rot_labels = c(45,0, 0, 0), offset_label =c(.5,5,0, 0), varnames = c(FALSE, TRUE), just_labels=c("center","right"), tl_varnames = FALSE), legend = FALSE) ``` Correspondence analysis, using the [ca package](https://cran.r-project.org/package=ca), shows that nearly 89% of the $\chi^2$ can be accounted for in two dimensions. ```{r housetasks-ca} require(ca) HT.ca <- ca(HouseTasks) summary(HT.ca, rows=FALSE, columns=FALSE) ``` The CA plot has a fairly simple interpretation: Dim1 is largely the distinction between tasks primarily done by the wife vs. the husband. Dim2 distinguishes tasks that are done singly vs. those that are done jointly. ```{r housetasks-ca-plot} plot(HT.ca, lines = TRUE) ``` So, we can use the `CA` method of `seriation::seriate()` to find the order of permutations of `Task` and `Who` along the CA dimensions. ```{r housetasks-seriation} require(seriation) order <- seriate(HouseTasks, method = "CA") # the permuted row and column labels rownames(HouseTasks)[order[[1]]] colnames(HouseTasks)[order[[2]]] ``` Now, use `seriation::permute()` to use `order` for the permutations of `Task` and `Who`, and plot the resulting mosaic: ```{r housetasks-mos2} # do the permutation HT_perm <- permute(HouseTasks, order, margin=1) mosaic(HT_perm, shade = TRUE, labeling = labeling_border(rot_labels = c(45,0, 0, 0), offset_label =c(.5,5,0, 0), varnames = c(FALSE, TRUE), just_labels=c("center","right"), tl_varnames = FALSE), legend = FALSE) ``` It is now easy to see the cluster of tasks (laundry and cooking) done largely by the wife at the top, and those (repairs, driving) done largely by the husband at the bottom. ## References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/mosaics.Rmd
## ----setup, include = FALSE--------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut02-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Old Sweave options # \SweaveOpts{engine=R,eps=TRUE,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{engine=R,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{prefix.string=fig/vcd-tut,eps=FALSE} # \SweaveOpts{keep.source=TRUE} # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ## ---- GSStab------------------------------------------------------------------ # Agresti (2002), table 3.11, p. 106 GSS <- data.frame( expand.grid(sex = c("female", "male"), party = c("dem", "indep", "rep")), count = c(279,165,73,47,225,191)) (GSStab <- xtabs(count ~ sex + party, data=GSS)) ## ---- xtabs-ex2--------------------------------------------------------------- # 2-Way Cross Tabulation library(gmodels) CrossTable(GSStab, prop.t=FALSE, prop.r=FALSE, prop.c=FALSE) ## ---- chisq------------------------------------------------------------------- (HairEye <- margin.table(HairEyeColor, c(1, 2))) chisq.test(HairEye) chisq.test(HairEye, simulate.p.value = TRUE) ## ----fisher------------------------------------------------------------------- fisher.test(GSStab) ## ----fisher-error, error=TRUE------------------------------------------------- fisher.test(HairEye) ## ---- mantel1----------------------------------------------------------------- # UC Berkeley Student Admissions mantelhaen.test(UCBAdmissions) ## ---- mantel2----------------------------------------------------------------- oddsratio(UCBAdmissions, log=FALSE) lor <- oddsratio(UCBAdmissions) # capture log odds ratios summary(lor) woolf_test(UCBAdmissions) ## ---- reorder3---------------------------------------------------------------- UCB <- aperm(UCBAdmissions, c(2, 1, 3)) dimnames(UCB)[[2]] <- c("Yes", "No") names(dimnames(UCB)) <- c("Sex", "Admit?", "Department") ## ----------------------------------------------------------------------------- col <- c("#99CCFF", "#6699CC", "#F9AFAF", "#6666A0", "#FF0000", "#000080") fourfold(UCB, mfrow=c(2,3), color=col) ## ----fourfold2, eval=FALSE---------------------------------------------------- # cotabplot(UCB, panel = cotab_fourfold) ## ----------------------------------------------------------------------------- doubledecker(Admit ~ Dept + Gender, data=UCBAdmissions[2:1,,]) ## ----------------------------------------------------------------------------- plot(lor, xlab="Department", ylab="Log Odds Ratio (Admit | Gender)") ## ---- table-form2, include=FALSE---------------------------------------------- ## A 4 x 4 table Agresti (2002, Table 2.8, p. 57) Job Satisfaction JobSat <- matrix(c(1,2,1,0, 3,3,6,1, 10,10,14,9, 6,7,12,11), 4, 4) dimnames(JobSat) = list(income=c("< 15k", "15-25k", "25-40k", "> 40k"), satisfaction=c("VeryD", "LittleD", "ModerateS", "VeryS")) JobSat <- as.table(JobSat) ## ---- jobsat------------------------------------------------------------------ JobSat ## ---- cmh1-------------------------------------------------------------------- CMHtest(JobSat, rscores=c(7.5,20,32.5,60)) ## ---- assoc1------------------------------------------------------------------ assocstats(GSStab) ## ---- gamma------------------------------------------------------------------- GKgamma(JobSat) ## ---- kappa------------------------------------------------------------------- data(SexualFun, package = "vcd") (K <- Kappa(SexualFun)) confint(K) ## ----------------------------------------------------------------------------- agree <- agreementplot(SexualFun, main="Is sex fun?") unlist(agree) ## ---- ca1--------------------------------------------------------------------- library(ca) ca(HairEye) ## ----ca-haireye, cap = "Correspondence analysis plot for the `HairEye` data"---- plot(ca(HairEye), main="Hair Color and Eye Color")
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/tests.R
--- title: "Tests of Independence" author: "Michael Friendly" date: "`r Sys.Date()`" output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] vignette: > %\VignetteIndexEntry{Tests of Independence} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut02-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Old Sweave options # \SweaveOpts{engine=R,eps=TRUE,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{engine=R,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{prefix.string=fig/vcd-tut,eps=FALSE} # \SweaveOpts{keep.source=TRUE} # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ``` OK, now we're ready to do some analyses. This vignette focuses on relatively simple non-parametric tests and measures of association. ## CrossTable For tabular displays, the `CrossTable()` function in the `gmodels` package produces cross-tabulations modeled after `PROC FREQ` in SAS or `CROSSTABS` in SPSS. It has a wealth of options for the quantities that can be shown in each cell. Recall the GSS data used earlier. ```{r, GSStab} # Agresti (2002), table 3.11, p. 106 GSS <- data.frame( expand.grid(sex = c("female", "male"), party = c("dem", "indep", "rep")), count = c(279,165,73,47,225,191)) (GSStab <- xtabs(count ~ sex + party, data=GSS)) ``` Generate a cross-table showing cell frequency and the cell contribution to $\chi^2$. ```{r, xtabs-ex2} # 2-Way Cross Tabulation library(gmodels) CrossTable(GSStab, prop.t=FALSE, prop.r=FALSE, prop.c=FALSE) ``` There are options to report percentages (row, column, cell), specify decimal places, produce Chi-square, Fisher, and McNemar tests of independence, report expected and residual values (pearson, standardized, adjusted standardized), include missing values as valid, annotate with row and column titles, and format as SAS or SPSS style output! See `help(CrossTable)` for details. ## Chi-square test For 2-way tables you can use `chisq.test()` to test independence of the row and column variable. By default, the $p$-value is calculated from the asymptotic chi-squared distribution of the test statistic. Optionally, the $p$-value can be derived via Monte Carlo simulation. ```{r, chisq} (HairEye <- margin.table(HairEyeColor, c(1, 2))) chisq.test(HairEye) chisq.test(HairEye, simulate.p.value = TRUE) ``` ## Fisher Exact Test {#sec:Fisher} `fisher.test(X)` provides an **exact test** of independence. `X` must be a two-way contingency table in table form. Another form, `fisher.test(X, Y)` takes two categorical vectors of the same length. For tables larger than $2 \times 2$ the method can be computationally intensive (or can fail) if the frequencies are not small. ```{r fisher} fisher.test(GSStab) ``` Fisher's test is meant for tables with small total sample size. It generates an error for the `HairEye` data with $n$=592 total frequency. ```{r fisher-error, error=TRUE} fisher.test(HairEye) ``` ## Mantel-Haenszel test and conditional association {#sec:mantel} Use the `mantelhaen.test(X)` function to perform a Cochran-Mantel-Haenszel $\chi^2$ chi test of the null hypothesis that two nominal variables are *conditionally independent*, $A \perp B \; | \; C$, in each stratum, assuming that there is no three-way interaction. `X` is a 3 dimensional contingency table, where the last dimension refers to the strata. The `UCBAdmissions` serves as an example of a $2 \times 2 \times 6$ table, with `Dept` as the stratifying variable. ```{r, mantel1} # UC Berkeley Student Admissions mantelhaen.test(UCBAdmissions) ``` The results show no evidence for association between admission and gender when adjusted for department. However, we can easily see that the assumption of equal association across the strata (no 3-way association) is probably violated. For $2 \times 2 \times k$ tables, this can be examined from the odds ratios for each $2 \times 2$ table (`oddsratio()`), and tested by using `woolf_test()` in `vcd`. ```{r, mantel2} oddsratio(UCBAdmissions, log=FALSE) lor <- oddsratio(UCBAdmissions) # capture log odds ratios summary(lor) woolf_test(UCBAdmissions) ``` ## Some plot methods ### Fourfold displays We can visualize the odds ratios of Admission for each department with fourfold displays using `fourfold()`. The cell frequencies $n_{ij}$ of each $2 \times 2$ table are shown as a quarter circle whose radius is proportional to $\sqrt{n_{ij}}$, so that its area is proportional to the cell frequency. ```{r, reorder3} UCB <- aperm(UCBAdmissions, c(2, 1, 3)) dimnames(UCB)[[2]] <- c("Yes", "No") names(dimnames(UCB)) <- c("Sex", "Admit?", "Department") ``` Confidence rings for the odds ratio allow a visual test of the null of no association; the rings for adjacent quadrants overlap *iff* the observed counts are consistent with the null hypothesis. In the extended version (the default), brighter colors are used where the odds ratio is significantly different from 1. The following lines produce @ref(fig:fourfold1). <!-- \footnote{The color values `col[3:4]` were modified from their default values --> <!-- to show a greater contrast between significant and insignificant associations here.} --> ```{r} #| fourfold1, #| h=5, w=7.5, #| cap = "Fourfold display for the `UCBAdmissions` data. Where the odds ratio differs #| significantly from 1.0, the confidence bands do not overlap, and the circle quadrants are #| shaded more intensely." col <- c("#99CCFF", "#6699CC", "#F9AFAF", "#6666A0", "#FF0000", "#000080") fourfold(UCB, mfrow=c(2,3), color=col) ``` Another `vcd` function, `cotabplot()`, provides a more general approach to visualizing conditional associations in contingency tables, similar to trellis-like plots produced by `coplot()` and lattice graphics. The `panel` argument supplies a function used to render each conditional subtable. The following gives a display (not shown) similar to @ref(fig:fourfold1). ```{r fourfold2, eval=FALSE} cotabplot(UCB, panel = cotab_fourfold) ``` ### Doubledecker plots When we want to view the conditional probabilities of a response variable (e.g., `Admit`) in relation to several factors, an alternative visualization is a `doubledecker()` plot. This plot is a specialized version of a mosaic plot, which highlights the levels of a response variable (plotted vertically) in relation to the factors (shown horizontally). The following call produces @ref(fig:doubledecker), where we use indexing on the first factor (`Admit`) to make `Admitted` the highlighted level. In this plot, the association between `Admit` and `Gender` is shown where the heights of the highlighted conditional probabilities do not align. The excess of females admitted in Dept A stands out here. ```{r} #| doubledecker, #| h=5, w=8, #| out.width = "75%", #| cap = "Doubledecker display for the `UCBAdmissions` data. The heights #| of the highlighted bars show the conditional probabilities of `Admit`, #| given `Dept` and `Gender`." doubledecker(Admit ~ Dept + Gender, data=UCBAdmissions[2:1,,]) ``` ### Odds ratio plots Finally, the there is a `plot()` method for `oddsratio` objects. By default, it shows the 95% confidence interval for the log odds ratio. @ref(fig:oddsratio) is produced by: ```{r} #| oddsratio, #| h=6, w=6, #| out.width = "60%", #| cap = "Log odds ratio plot for the `UCBAdmissions` data." plot(lor, xlab="Department", ylab="Log Odds Ratio (Admit | Gender)") ``` {#fig:oddsratio} ## Cochran-Mantel-Haenszel tests for ordinal factors {#sec:CMH} The standard $\chi^2$ tests for association in a two-way table treat both table factors as nominal (unordered) categories. When one or both factors of a two-way table are quantitative or ordinal, more powerful tests of association may be obtained by taking ordinality into account, using row and or column scores to test for linear trends or differences in row or column means. More general versions of the CMH tests (Landis etal., 1978) [@Landis-etal:1978] are provided by assigning numeric scores to the row and/or column variables. For example, with two ordinal factors (assumed to be equally spaced), assigning integer scores, `1:R` and `1:C` tests the linear $\times$ linear component of association. This is statistically equivalent to the Pearson correlation between the integer-scored table variables, with $\chi^2 = (n-1) r^2$, with only 1 $df$ rather than $(R-1)\times(C-1)$ for the test of general association. When only one table variable is ordinal, these general CMH tests are analogous to an ANOVA, testing whether the row mean scores or column mean scores are equal, again consuming fewer $df$ than the test of general association. The `CMHtest()` function in `vcdExtra` calculates these various CMH tests for two possibly ordered factors, optionally stratified other factor(s). ***Example***: ```{r, table-form2, include=FALSE} ## A 4 x 4 table Agresti (2002, Table 2.8, p. 57) Job Satisfaction JobSat <- matrix(c(1,2,1,0, 3,3,6,1, 10,10,14,9, 6,7,12,11), 4, 4) dimnames(JobSat) = list(income=c("< 15k", "15-25k", "25-40k", "> 40k"), satisfaction=c("VeryD", "LittleD", "ModerateS", "VeryS")) JobSat <- as.table(JobSat) ``` Recall the $4 \times 4$ table, `JobSat` introduced in \@ref(sec:creating), ```{r, jobsat} JobSat ``` Treating the `satisfaction` levels as equally spaced, but using midpoints of the `income` categories as row scores gives the following results: ```{r, cmh1} CMHtest(JobSat, rscores=c(7.5,20,32.5,60)) ``` Note that with the relatively small cell frequencies, the test for general give no evidence for association. However, the the `cor` test for linear x linear association on 1 df is nearly significant. The `coin` package contains the functions `cmh_test()` and `lbl_test()` for CMH tests of general association and linear x linear association respectively. ## Measures of Association There are a variety of statistical measures of *strength* of association for contingency tables--- similar in spirit to $r$ or $r^2$ for continuous variables. With a large sample size, even a small degree of association can show a significant $\chi^2$, as in the example below for the `GSS` data. The `assocstats()` function in `vcd` calculates the $\phi$ contingency coefficient, and Cramer's V for an $r \times c$ table. The input must be in table form, a two-way $r \times c$ table. It won't work with `GSS` in frequency form, but by now you should know how to convert. ```{r, assoc1} assocstats(GSStab) ``` For tables with ordinal variables, like `JobSat`, some people prefer the Goodman-Kruskal $\gamma$ statistic [@vcd:Agresti:2002, \S 2.4.3] based on a comparison of concordant and discordant pairs of observations in the case-form equivalent of a two-way table. ```{r, gamma} GKgamma(JobSat) ``` A web article by Richard Darlington, [http://node101.psych.cornell.edu/Darlington/crosstab/TABLE0.HTM] gives further description of these and other measures of association. ## Measures of Agreement The `Kappa()` function in the `vcd` package calculates Cohen's $\kappa$ and weighted $\kappa$ for a square two-way table with the same row and column categories [@Cohen:60]. \footnote{ Don't confuse this with `kappa()` in base R that computes something entirely different (the condition number of a matrix). } Normal-theory $z$-tests are obtained by dividing $\kappa$ by its asymptotic standard error (ASE). A `confint()` method for `Kappa` objects provides confidence intervals. ```{r, kappa} data(SexualFun, package = "vcd") (K <- Kappa(SexualFun)) confint(K) ``` A visualization of agreement [@Bangdiwala:87], both unweighted and weighted for degree of departure from exact agreement is provided by the `agreementplot()` function. @fig(fig:agreesex) shows the agreementplot for the `SexualFun` data, produced as shown below. The Bangdiwala measures (returned by the function) represent the proportion of the shaded areas of the diagonal rectangles, using weights $w_1$ for exact agreement, and $w_2$ for partial agreement one step from the main diagonal. ```{r} #| agreesex, #| h=6, w=7, #| out.width = "70%", #| cap = "Agreement plot for the `SexualFun` data." agree <- agreementplot(SexualFun, main="Is sex fun?") unlist(agree) ``` In other examples, the agreement plot can help to show *sources* of disagreement. For example, when the shaded boxes are above or below the diagonal (red) line, a lack of exact agreement can be attributed in part to different frequency of use of categories by the two raters-- lack of *marginal homogeneity*. ## Correspondence analysis Correspondence analysis is a technique for visually exploring relationships between rows and columns in contingency tables. The `ca` package gives one implementation. For an $r \times c$ table, the method provides a breakdown of the Pearson $\chi^2$ for association in up to $M = \min(r-1, c-1)$ dimensions, and finds scores for the row ($x_{im}$) and column ($y_{jm}$) categories such that the observations have the maximum possible correlations.% ^[Related methods are the non-parametric CMH tests using assumed row/column scores (\@ref(sec:CMH), the analogous `glm()` model-based methods (\@ref(sec:CMH), and the more general RC models which can be fit using `gnm()`. Correspondence analysis differs in that it is a primarily descriptive/exploratory method (no significance tests), but is directly tied to informative graphic displays of the row/column categories.] Here, we carry out a simple correspondence analysis of the `HairEye` data. The printed results show that nearly 99% of the association between hair color and eye color can be accounted for in 2 dimensions, of which the first dimension accounts for 90%. ```{r, ca1} library(ca) ca(HairEye) ``` The resulting `ca` object can be plotted just by running the `plot()` method on the `ca` object, giving the result in \@ref(fig:ca-haireye). `plot.ca()` does not allow labels for dimensions; these can be added with `title()`. It can be seen that most of the association is accounted for by the ordering of both hair color and eye color along Dimension 1, a dark to light dimension. ```{r ca-haireye, cap = "Correspondence analysis plot for the `HairEye` data"} plot(ca(HairEye), main="Hair Color and Eye Color") ``` ## References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/inst/doc/tests.Rmd
--- title: "Continuous predictors" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Continuous predictors} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut05-", fig.align = "center", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Old Sweave options # \SweaveOpts{engine=R,eps=TRUE,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{engine=R,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{prefix.string=fig/vcd-tut,eps=FALSE} # \SweaveOpts{keep.source=TRUE} # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ``` When continuous predictors are available---and potentially important---in explaining a categorical outcome, models for that outcome include: logistic regression (binary response), the proportional odds model (ordered polytomous response), multinomial (generalized) logistic regression. Many of these are special cases of the generalized linear model using the `"poisson"` or `"binomial"` family and their relatives. ## Spine and conditional density plots {#sec:spine} I don't go into fitting such models here, but I would be remiss not to illustrate some visualizations in `vcd` that are helpful here. The first of these is the spine plot or spinogram [@vcd:Hummel:1996], produced with `spine()`. These are special cases of mosaic plots with specific spacing and shading to show how a categorical response varies with a continuous or categorical predictor. They are also a generalization of stacked bar plots where not the heights but the *widths* of the bars corresponds to the relative frequencies of `x`. The heights of the bars then correspond to the conditional relative frequencies of `y` in every `x` group. ***Example***: For the `Arthritis` data, we can see how `Improved` varies with `Age` as follows. `spine()` takes a formula of the form `y ~ x` with a single dependent factor and a single explanatory variable `x` (a numeric variable or a factor). The range of a numeric variable`x` is divided into intervals based on the `breaks` argument, and stacked bars are drawn to show the distribution of `y` as `x` varies. As shown below, the discrete table that is visualized is returned by the function. ```{r, spine1} #| spine1, #| fig.height = 6, #| fig.width = 6, #| fig.show = "hold", #| out.width = "46%", #| fig.align = "center", #| cap = "Spine plots for the `Arthritis` data" (spine(Improved ~ Age, data = Arthritis, breaks = 3)) (spine(Improved ~ Age, data = Arthritis, breaks = "Scott")) ``` The conditional density plot [@vcd:Hofmann+Theus] is a further generalization. This visualization technique is similar to spinograms, but uses a smoothing approach rather than discretizing the explanatory variable. As well, it uses the original `x` axis and not a distorted one. ```{r} #| cdplot, #| fig.height = 5, #| fig.width = 5, #| cap = "Conditional density plot for the `Arthritis` data showing the variation of Improved with Age." cdplot(Improved ~ Age, data = Arthritis) ``` In such plots, it is useful to also see the distribution of the observations across the horizontal axis, e.g., with a `rug()` plot. \@ref{fig:cd-plot} uses `cdplot()` from the `graphics` package rather than `cd_plot()` from `vcd`, and is produced with ```{r} #| cdplot1, #| fig.height = 5, #| fig.width = 5, cdplot(Improved ~ Age, data = Arthritis) with(Arthritis, rug(jitter(Age), col="white", quiet=TRUE)) ``` From this figure it can be easily seen that the proportion of patients reporting Some or Marked improvement increases with Age, but there are some peculiar bumps in the distribution. These may be real or artifactual, but they would be hard to see with most other visualization methods. When we switch from non-parametric data exploration to parametric statistical models, such effects are easily missed. ## Model-based plots: effect plots and `ggplot2 plots` {#sec:modelplots} The nonparametric conditional density plot uses smoothing methods to convey the distributions of the response variable, but displays that are simpler to interpret can often be obtained by plotting the predicted response from a parametric model. For complex `glm()` models with interaction effects, the `effects` package provides the most useful displays, plotting the predicted values for a given term, averaging over other predictors not included in that term. I don't illustrate this here, but see @effects:1,@effects:2 and `help(package="effects")`. Here I just briefly illustrate the capabilities of the `ggplot2` package for model-smoothed plots of categorical responses in `glm()` models. ***Example***: The `Donner` data frame in `vcdExtra` gives details on the survival of 90 members of the Donner party, a group of people who attempted to migrate to California in 1846. They were trapped by an early blizzard on the eastern side of the Sierra Nevada mountains, and before they could be rescued, nearly half of the party had died. What factors affected who lived and who died? ```{r, donner1} data(Donner, package="vcdExtra") str(Donner) ``` A potential model of interest is the logistic regression model for $Pr(survived)$, allowing separate fits for males and females as a function of `age`. The key to this is the `stat_smooth()` function, using `method = "glm", method.args = list(family = binomial)`. The `formula = y ~ x` specifies a linear fit on the logit scale (\@ref{fig:donner3}, left) ```{r, donner2a, fig=FALSE, eval=FALSE} # separate linear fits on age for M/F ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ x, alpha = 0.2, size=2, aes(fill = sex)) ``` Alternatively, we can allow a quadratic relation with `age` by specifying `formula = y ~ poly(x,2)` (@ref(fig:donner3), right). ```{r, donner2b, fig=FALSE, eval=FALSE} # separate quadratics ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ poly(x,2), alpha = 0.2, size=2, aes(fill = sex)) ``` ```{r} #| donner3a, #| echo = FALSE, #| fig.height = 6, #| fig.width = 6, #| fig.show = "hold", #| out.width = "46%", #| cap = "Logistic regression plots for the `Donner` data showing survival vs. age, by sex. Left: linear logistic model; right: quadratic model {#fig:donner3}" # separate linear fits on age for M/F ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ x, alpha = 0.2, size=2, aes(fill = sex)) # separate quadratics ggplot(Donner, aes(age, survived, color = sex)) + geom_point(position = position_jitter(height = 0.02, width = 0)) + stat_smooth(method = "glm", method.args = list(family = binomial), formula = y ~ poly(x,2), alpha = 0.2, size=2, aes(fill = sex)) ``` These plots very nicely show (a) the fitted $Pr(survived)$ for males and females; (b) confidence bands around the smoothed model fits and (c) the individual observations by jittered points at 0 and 1 for those who died and survived, respectively. # References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/vignettes/continuous.Rmd
--- title: "Creating and manipulating frequency tables" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Creating and manipulating frequency tables} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut01-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # Old Sweave options # \SweaveOpts{engine=R,eps=TRUE,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{engine=R,height=6,width=7,results=hide,fig=FALSE,echo=TRUE} # \SweaveOpts{prefix.string=fig/vcd-tut,eps=FALSE} # \SweaveOpts{keep.source=TRUE} # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ``` R provides many methods for creating frequency and contingency tables. Several are described below. In the examples below, we use some real examples and some anonymous ones, where the variables `A`, `B`, and `C` represent categorical variables, and `X` represents an arbitrary R data object. ## Forms of frequency data The first thing you need to know is that categorical data can be represented in three different forms in R, and it is sometimes necessary to convert from one form to another, for carrying out statistical tests, fitting models or visualizing the results. Once a data object exists in R, you can examine its complete structure with the `str()` function, or view the names of its components with the `names()` function. ### Case form Categorical data in case form are simply data frames containing individual observations, with one or more factors, used as the classifying variables. In case form, there may also be numeric covariates. The total number of observations is `nrow(X)`, and the number of variables is `ncol(X)`. ***Example***: The `Arthritis` data is available in case form in the `vcd` package. There are two explanatory factors: `Treatment` and `Sex`. `Age` is a numeric covariate, and `Improved` is the response--- an ordered factor, with levels `r paste(levels(Arthritis$Improved),collapse=' < ')`. Excluding `Age`, this represents a $2 \times 2 \times 3$ contingency table for `Treatment`, `Sex` and `Improved`, but in case form. ```{r, case-form} names(Arthritis) # show the variables str(Arthritis) # show the structure head(Arthritis,5) # first 5 observations, same as Arthritis[1:5,] ``` ### Frequency form Data in frequency form is also a data frame containing one or more factors, and a frequency variable, often called `Freq` or `count`. The total number of observations is: `sum(X$Freq)`, `sum(X[,"Freq"])` or some equivalent form. The number of cells in the table is given by `nrow(X)`. ***Example***: For small frequency tables, it is often convenient to enter them in frequency form using `expand.grid()` for the factors and `c()` to list the counts in a vector. The example below, from [@vcd:Agresti:2002] gives results for the 1991 General Social Survey, with respondents classified by sex and party identification. ```{r, frequency-form} # Agresti (2002), table 3.11, p. 106 GSS <- data.frame( expand.grid(sex = c("female", "male"), party = c("dem", "indep", "rep")), count = c(279,165,73,47,225,191)) GSS names(GSS) str(GSS) sum(GSS$count) ``` ### Table form Table form data is represented by a `matrix`, `array` or `table` object, whose elements are the frequencies in an $n$-way table. The variable names (factors) and their levels are given by `dimnames(X)`. The total number of observations is `sum(X)`. The number of dimensions of the table is `length(dimnames(X))`, and the table sizes are given by `sapply(dimnames(X), length)`. ***Example***: The `HairEyeColor` is stored in table form in `vcd`. ```{r, table-form1} str(HairEyeColor) # show the structure sum(HairEyeColor) # number of cases sapply(dimnames(HairEyeColor), length) # table dimension sizes ``` ***Example***: Enter frequencies in a matrix, and assign `dimnames`, giving the variable names and category labels. Note that, by default, `matrix()` uses the elements supplied by *columns* in the result, unless you specify `byrow=TRUE`. ```{r, table-form2} # A 4 x 4 table Agresti (2002, Table 2.8, p. 57) Job Satisfaction JobSat <- matrix(c( 1, 2, 1, 0, 3, 3, 6, 1, 10,10,14, 9, 6, 7,12,11), 4, 4) dimnames(JobSat) = list( income = c("< 15k", "15-25k", "25-40k", "> 40k"), satisfaction = c("VeryD", "LittleD", "ModerateS", "VeryS") ) JobSat ``` `JobSat` is a **matrix**, not an object of `class("table")`, and some functions are happier with tables than matrices. You can coerce it to a table with `as.table()`, ```{r, table-form3} JobSat <- as.table(JobSat) str(JobSat) ``` ## Ordered factors and reordered tables {#sec:ordered-factors} In table form, the values of the table factors are ordered by their position in the table. Thus in the `JobSat` data, both `income` and `satisfaction` represent ordered factors, and the *positions* of the values in the rows and columns reflects their ordered nature. Yet, for analysis, there are times when you need *numeric* values for the levels of ordered factors in a table, e.g., to treat a factor as a quantitative variable. In such cases, you can simply re-assign the `dimnames` attribute of the table variables. For example, here, we assign numeric values to `income` as the middle of their ranges, and treat `satisfaction` as equally spaced with integer scores. ```{r, relevel, eval=FALSE} dimnames(JobSat)$income <- c(7.5,20,32.5,60) dimnames(JobSat)$satisfaction <- 1:4 ``` For the `HairEyeColor` data, hair color and eye color are ordered arbitrarily. For visualizing the data using mosaic plots and other methods described below, it turns out to be more useful to assure that both hair color and eye color are ordered from dark to light. Hair colors are actually ordered this way already, and it is easiest to re-order eye colors by indexing. Again `str()` is your friend. ```{r, reorder1} HairEyeColor <- HairEyeColor[, c(1,3,4,2), ] str(HairEyeColor) ``` This is also the order for both hair color and eye color shown in the result of a correspondence analysis (@ref(fig:ca-haireye) below. With data in case form or frequency form, when you have ordered factors represented with character values, you must ensure that they are treated as ordered in R. <!-- \footnote{In SAS, many procedures offer the option --> <!-- `order = data | internal | formatted` to allow character values --> <!-- to be ordered according to (a) their order in the data set, (b) --> <!-- sorted internal value, or (c) sorted formatted representation --> <!-- provided by a SAS format. --> <!-- } --> Imagine that the `Arthritis` data was read from a text file. By default the `Improved` will be ordered alphabetically: `Marked`, `None`, `Some` --- not what we want. In this case, the function `ordered()` (and others) can be useful. ```{r, reorder2, echo=TRUE, eval=FALSE} Arthritis <- read.csv("arthritis.txt",header=TRUE) Arthritis$Improved <- ordered(Arthritis$Improved, levels=c("None", "Some", "Marked") ) ``` The dataset `Arthritis` in the `vcd` package is a data.frame in this form With this order of `Improved`, the response in this data, a mosaic display of `Treatment` and `Improved` (@ref(fig:arthritis) shows a clearly interpretable pattern. The original version of `mosaic` in the `vcd` package required the input to be a contingency table in array form, so we convert using `xtabs()`. <!-- ```{r Arthritis, height=6, width=7, fig.cap="Mosaic plot for the `Arthritis` data ..."} --> ```{r} #| Arthritis, #| fig.height = 6, #| fig.width = 6, #| fig.cap = "Mosaic plot for the `Arthritis` data, showing the marginal model of independence for Treatment and Improved. Age, a covariate, and Sex are ignored here." data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) mosaic(art, gp = shading_max, split_vertical = TRUE, main="Arthritis: [Treatment] [Improved]") ``` Several data sets in the package illustrate the salutary effects of reordering factor levels in mosaic displays and other analyses. See: * `help(AirCrash)` * `help(Glass)` * `help(HouseTasks)` The [seriate](https://CRAN.R-project.org/package=seriation) package now contains a general method to permute the row and column variables in a table according to the result of a correspondence analysis, using scores on the first CA dimension. ### Re-ordering dimensions Finally, there are situations where, particularly for display purposes, you want to re-order the *dimensions* of an $n$-way table, or change the labels for the variables or levels. This is easy when the data are in table form: `aperm()` permutes the dimensions, and assigning to `names` and `dimnames` changes variable names and level labels respectively. We will use the following version of `UCBAdmissions` in \@ref(sec:mantel) below. ^[Changing `Admit` to `Admit?` might be useful for display purposes, but is dangerous--- because it is then difficult to use that variable name in a model formula. See \@ref(sec:tips) for options `labeling_args` and `set_labels`to change variable and level names for displays in the `strucplot` framework.] ```{r, reorder3} UCB <- aperm(UCBAdmissions, c(2, 1, 3)) dimnames(UCB)[[2]] <- c("Yes", "No") names(dimnames(UCB)) <- c("Sex", "Admit?", "Department") # display as a flattened table stats::ftable(UCB) ``` ## `structable()` {#sec:structable} For 3-way and larger tables the `structable()` function in `vcd` provides a convenient and flexible tabular display. The variables assigned to the rows and columns of a two-way display can be specified by a model formula. ```{r, structable} structable(HairEyeColor) # show the table: default structable(Hair+Sex ~ Eye, HairEyeColor) # specify col ~ row variables ``` It also returns an object of class `"structable"` which may be plotted with `mosaic()` (not shown here). ```{r, structable1,eval=FALSE} HSE < - structable(Hair+Sex ~ Eye, HairEyeColor) # save structable object mosaic(HSE) # plot it ``` ## `table()` and friends {#sec:table} You can generate frequency tables from factor variables using the `table()` function, tables of proportions using the `prop.table()` function, and marginal frequencies using `margin.table()`. For these examples, create some categorical vectors: ```{r, table-setup} n=500 A <- factor(sample(c("a1","a2"), n, rep=TRUE)) B <- factor(sample(c("b1","b2"), n, rep=TRUE)) C <- factor(sample(c("c1","c2"), n, rep=TRUE)) mydata <- data.frame(A,B,C) ``` These lines illustrate `table`-related functions: ```{r, table-ex1} # 2-Way Frequency Table attach(mydata) mytable <- table(A,B) # A will be rows, B will be columns mytable # print table margin.table(mytable, 1) # A frequencies (summed over B) margin.table(mytable, 2) # B frequencies (summed over A) prop.table(mytable) # cell percentages prop.table(mytable, 1) # row percentages prop.table(mytable, 2) # column percentages ``` `table()` can also generate multidimensional tables based on 3 or more categorical variables. In this case, you can use the `ftable()` or `structable()` function to print the results more attractively. ```{r, table-ex2} # 3-Way Frequency Table mytable <- table(A, B, C) ftable(mytable) ``` `table()` ignores missing values by default. To include `NA` as a category in counts, include the table option `exclude=NULL` if the variable is a vector. If the variable is a factor you have to create a new factor using \code{newfactor <- factor(oldfactor, exclude=NULL)}. ## `xtabs()` {#sec:xtabs} The `xtabs()` function allows you to create cross-tabulations of data using formula style input. This typically works with case-form data supplied in a data frame or a matrix. The result is a contingency table in array format, whose dimensions are determined by the terms on the right side of the formula. ```{r, xtabs-ex1} # 3-Way Frequency Table mytable <- xtabs(~A+B+C, data=mydata) ftable(mytable) # print table summary(mytable) # chi-square test of indepedence ``` If a variable is included on the left side of the formula, it is assumed to be a vector of frequencies (useful if the data have already been tabulated in frequency form). ```{r, xtabs-ex2} (GSStab <- xtabs(count ~ sex + party, data=GSS)) summary(GSStab) ``` ## Collapsing over table factors: `aggregate()`, `margin.table()` and `apply()` It sometimes happens that we have a data set with more variables or factors than we want to analyse, or else, having done some initial analyses, we decide that certain factors are not important, and so should be excluded from graphic displays by collapsing (summing) over them. For example, mosaic plots and fourfold displays are often simpler to construct from versions of the data collapsed over the factors which are not shown in the plots. The appropriate tools to use again depend on the form in which the data are represented--- a case-form data frame, a frequency-form data frame (`aggregate()`), or a table-form array or table object (`margin.table()` or `apply()`). When the data are in frequency form, and we want to produce another frequency data frame, `aggregate()` is a handy tool, using the argument `FUN=sum` to sum the frequency variable over the factors *not* mentioned in the formula. ***Example***: The data frame `DaytonSurvey` in the `vcdExtra` package represents a $2^5$ table giving the frequencies of reported use (``ever used?'') of alcohol, cigarettes and marijuana in a sample of high school seniors, also classified by sex and race. ```{r, dayton1} data("DaytonSurvey", package="vcdExtra") str(DaytonSurvey) head(DaytonSurvey) ``` To focus on the associations among the substances, we want to collapse over sex and race. The right-hand side of the formula used in the call to `aggregate()` gives the factors to be retained in the new frequency data frame, `Dayton.ACM.df`. ```{r, dayton2} # data in frequency form # collapse over sex and race Dayton.ACM.df <- aggregate(Freq ~ cigarette+alcohol+marijuana, data=DaytonSurvey, FUN=sum) Dayton.ACM.df ``` When the data are in table form, and we want to produce another table, `apply()` with `FUN=sum` can be used in a similar way to sum the table over dimensions not mentioned in the `MARGIN` argument. `margin.table()` is just a wrapper for `apply()` using the `sum()` function. ***Example***: To illustrate, we first convert the `DaytonSurvey` to a 5-way table using `xtabs()`, giving `Dayton.tab`. ```{r, dayton3} # in table form Dayton.tab <- xtabs(Freq ~ cigarette+alcohol+marijuana+sex+race, data=DaytonSurvey) structable(cigarette+alcohol+marijuana ~ sex+race, data=Dayton.tab) ``` Then, use `apply()` on `Dayton.tab` to give the 3-way table `Dayton.ACM.tab` summed over sex and race. The elements in this new table are the column sums for `Dayton.tab` shown by `structable()` just above. ```{r, dayton4} # collapse over sex and race Dayton.ACM.tab <- apply(Dayton.tab, MARGIN=1:3, FUN=sum) Dayton.ACM.tab <- margin.table(Dayton.tab, 1:3) # same result structable(cigarette+alcohol ~ marijuana, data=Dayton.ACM.tab) ``` Many of these operations can be performed using the `**ply()` functions in the [`plyr`]( https://CRAN.R-project.org/package=plyr) package. For example, with the data in a frequency form data frame, use `ddply()` to collapse over unmentioned factors, and `plyr::summarise()` as the function to be applied to each piece. <!-- \footnote{ --> <!-- Ugh. This `plyr` function clashes with a function of the same name in `vcdExtra`. --> <!-- In this document I will use the explicit double-colon notation to keep them --> <!-- separate. --> <!-- } --> ```{r, dayton5} library(plyr) Dayton.ACM.df <- plyr::ddply(DaytonSurvey, .(cigarette, alcohol, marijuana), plyr::summarise, Freq=sum(Freq)) Dayton.ACM.df ``` ## Collapsing table levels: `collapse.table()` A related problem arises when we have a table or array and for some purpose we want to reduce the number of levels of some factors by summing subsets of the frequencies. For example, we may have initially coded Age in 10-year intervals, and decide that, either for analysis or display purposes, we want to reduce Age to 20-year intervals. The `collapse.table()` function in `vcdExtra` was designed for this purpose. ***Example***: Create a 3-way table, and collapse Age from 10-year to 20-year intervals. First, we generate a $2 \times 6 \times 3$ table of random counts from a Poisson distribution with mean of 100. ```{r, collapse1} # create some sample data in frequency form sex <- c("Male", "Female") age <- c("10-19", "20-29", "30-39", "40-49", "50-59", "60-69") education <- c("low", 'med', 'high') data <- expand.grid(sex=sex, age=age, education=education) counts <- rpois(36, 100) # random Possion cell frequencies data <- cbind(data, counts) # make it into a 3-way table t1 <- xtabs(counts ~ sex + age + education, data=data) structable(t1) ``` Now collapse `age` to 20-year intervals, and `education` to 2 levels. In the arguments, levels of `age` and `education` given the same label are summed in the resulting smaller table. ```{r, collapse2} # collapse age to 3 levels, education to 2 levels t2 <- collapse.table(t1, age=c("10-29", "10-29", "30-49", "30-49", "50-69", "50-69"), education=c("<high", "<high", "high")) structable(t2) ``` ## Collapsing table levels: `dplyr` For data sets in frequency form or case form, factor levels can be collapsed by recoding the levels to some grouping. One handy function for this is `dplyr::case_match()` ***Example***: The `vcdExtra::Titanicp` data set contains information on 1309 passengers on the _RMS Titanic_, including `sibsp`, the number of (0:8) siblings or spouses aboard, and `parch` (0:6), the number of parents or children aboard, but the table is quite sparse. ```{r titanicp1} table(Titanicp$sibsp, Titanicp$parch) ``` For purposes of analysis, we might want to collapse both of these to the levels `0, 1, 2+`. Here's how: ```{r titanicp2} library(dplyr) Titanicp <- Titanicp |> mutate(sibspF = case_match(sibsp, 0 ~ "0", 1 ~ "1", 2:max(sibsp) ~ "2+")) |> mutate(sibspF = ordered(sibspF)) |> mutate(parchF = case_match(parch, 0 ~ "0", 1 ~ "1", 2:max(parch) ~ "2+")) |> mutate(parchF = ordered(parchF)) table(Titanicp$sibspF, Titanicp$parchF) ``` `car::recode()` is a similar function, but with a less convenient interface. The [`forcats`]( https://CRAN.R-project.org/package=forcats) package provides a collection of functions for reordering the levels of a factor or grouping categories according to their frequency: * `forcats::fct_reorder()`: Reorder a factor by another variable. * `forcats::fct_infreq()`: Reorder a factor by the frequency of values. * `forcats::fct_relevel()`: Change the order of a factor by hand. * `forcats::fct_lump()`: Collapse the least/most frequent values of a factor into “other”. * `forcats::fct_collapse()`: Collapse factor levels into manually defined groups. * `forcats::fct_recode()`: Change factor levels by hand. ## Converting among frequency tables and data frames As we've seen, a given contingency table can be represented equivalently in different forms, but some R functions were designed for one particular representation. The table below shows some handy tools for converting from one form to another. <!-- [htb] --> <!-- \caption{Tools for converting among different forms for categorical data} {#tab:convert} --> <!-- {llll} --> <!-- \hline --> <!-- & \multicolumn{3}{c}{**To this**} \\ --> <!-- **From this** & Case form & Frequency form & Table form \\ --> <!-- \hline --> <!-- Case form & noop & `xtabs(~A+B)` & `table(A,B)` \\ --> <!-- Frequency form & `expand.dft(X)` & noop & `xtabs(count~A+B)`\\ --> <!-- Table form & `expand.dft(X)` & `as.data.frame(X)` & noop \\ --> <!-- \hline --> | **From this** | | **To this** | | |:-----------------|:--------------------|:---------------------|-------------------| | | _Case form_ | _Frequency form_ | _Table form_ | | _Case form_ | noop | `xtabs(~A+B)` | `table(A,B)` | | _Frequency form_ | `expand.dft(X)` | noop | `xtabs(count~A+B)`| | _Table form_ | `expand.dft(X)` | `as.data.frame(X)` | noop | For example, a contingency table in table form (an object of `class(table)`) can be converted to a data.frame with `as.data.frame()`. ^[Because R is object-oriented, this is actually a short-hand for the function `as.data.frame.table()`.] The resulting `data.frame` contains columns representing the classifying factors and the table entries (as a column named by the `responseName` argument, defaulting to `Freq`. This is the inverse of `xtabs()`. ***Example***: Convert the `GSStab` in table form to a data.frame in frequency form. ```{r, convert-ex1} as.data.frame(GSStab) ``` ***Example***: Convert the `Arthritis` data in case form to a 3-way table of `Treatment` $\times$ `Sex` $\times$ `Improved`. Note the use of `with()` to avoid having to use `Arthritis\$Treatment` etc. within the call to `table()`.% ^[`table()` does not allow a `data` argument to provide an environment in which the table variables are to be found. In the examples in \@ref(sec:table) I used `attach(mydata)` for this purpose, but `attach()` leaves the variables in the global environment, while `with()` just evaluates the `table()` expression in a temporary environment of the data.] ```{r, convert-ex2} Art.tab <- with(Arthritis, table(Treatment, Sex, Improved)) str(Art.tab) ftable(Art.tab) ``` There may also be times that you will need an equivalent case form `data.frame` with factors representing the table variables rather than the frequency table. For example, the `mca()` function in package `MASS` only operates on data in this format. Marc Schwartz initially provided code for `expand.dft()` on the Rhelp mailing list for converting a table back into a case form `data.frame`. This function is included in `vcdExtra`. ***Example***: Convert the `Arthritis` data in table form (`Art.tab`) back to a `data.frame` in case form, with factors `Treatment`, `Sex` and `Improved`. ```{r, convert-ex3} Art.df <- expand.dft(Art.tab) str(Art.df) ``` ## A complex example {#sec:complex} If you've followed so far, you're ready for a more complicated example. The data file, `tv.dat` represents a 4-way table of size $5 \times 11 \times 5 \times 3$ where the table variables (unnamed in the file) are read as `V1` -- `V4`, and the cell frequency is read as `V5`. The file, stored in the `doc/extdata` directory of `vcdExtra`, can be read as follows: ```{r, tv1} tv.data<-read.table(system.file("extdata","tv.dat", package="vcdExtra")) head(tv.data,5) ``` For a local file, just use `read.table()` in this form: ```{r, tv2,eval=FALSE} tv.data<-read.table("C:/R/data/tv.dat") ``` The data `tv.dat` came from the initial implementation of mosaic displays in R by Jay Emerson. In turn, they came from the initial development of mosaic displays [@vcd:Hartigan+Kleiner:1984] that illustrated the method with data on a large sample of TV viewers whose behavior had been recorded for the Neilsen ratings. This data set contains sample television audience data from Neilsen Media Research for the week starting November 6, 1995. The table variables are: * `V1`-- values 1:5 correspond to the days Monday--Friday; * `V2`-- values 1:11 correspond to the quarter hour times 8:00PM through 10:30PM; * `V3`-- values 1:5 correspond to ABC, CBS, NBC, Fox, and non-network choices; * `V4`-- values 1:3 correspond to transition states: turn the television Off, Switch channels, or Persist in viewing the current channel. We are interested just the cell frequencies, and rely on the facts that the (a) the table is complete--- there are no missing cells, so `nrow(tv.data)` = `r nrow(tv.data)`; (b) the observations are ordered so that `V1` varies most rapidly and `V4` most slowly. From this, we can just extract the frequency column and reshape it into an array. [That would be dangerous if any observations were out of order.] ```{r, tv3} TV <- array(tv.data[,5], dim=c(5,11,5,3)) dimnames(TV) <- list(c("Monday","Tuesday","Wednesday","Thursday","Friday"), c("8:00","8:15","8:30","8:45","9:00","9:15","9:30", "9:45","10:00","10:15","10:30"), c("ABC","CBS","NBC","Fox","Other"), c("Off","Switch","Persist")) names(dimnames(TV))<-c("Day", "Time", "Network", "State") ``` More generally (even if there are missing cells), we can use `xtabs()` (or `plyr::daply()`) to do the cross-tabulation, using `V5` as the frequency variable. Here's how to do this same operation with `xtabs()`: ```{r, tv3a,eval=FALSE} TV <- xtabs(V5 ~ ., data=tv.data) dimnames(TV) <- list(Day = c("Monday","Tuesday","Wednesday","Thursday","Friday"), Time = c("8:00","8:15","8:30","8:45","9:00","9:15","9:30", "9:45","10:00","10:15","10:30"), Network = c("ABC","CBS","NBC","Fox","Other"), State = c("Off","Switch","Persist")) # table dimensions dim(TV) ``` But this 4-way table is too large and awkward to work with. Among the networks, Fox and Other occur infrequently. We can also cut it down to a 3-way table by considering only viewers who persist with the current station. ^[This relies on the fact that that indexing an array drops dimensions of length 1 by default, using the argument `drop=TRUE`; the result is coerced to the lowest possible dimension.] ```{r, tv4} TV2 <- TV[,,1:3,] # keep only ABC, CBS, NBC TV2 <- TV2[,,,3] # keep only Persist -- now a 3 way table structable(TV2) ``` Finally, for some purposes, we might want to collapse the 11 times into a smaller number. Half-hour time slots make more sense. Here, we use `as.data.frame.table()` to convert the table back to a data frame, `levels()` to re-assign the values of `Time`, and finally, `xtabs()` to give a new, collapsed frequency table. ```{r, tv5} TV.df <- as.data.frame.table(TV2) levels(TV.df$Time) <- c(rep("8:00", 2), rep("8:30", 2), rep("9:00", 2), rep("9:30", 2), rep("10:00",2), "10:30" ) TV3 <- xtabs(Freq ~ Day + Time + Network, TV.df) structable(Day ~ Time+Network, TV3) ``` We've come this far, so we might as well show a mosaic display. This is analogous to that used by @vcd:Hartigan+Kleiner:1984. ```{r tv-mosaic1, fig.height=6, fig.width=7} mosaic(TV3, shade = TRUE, labeling = labeling_border(rot_labels = c(0, 0, 0, 90))) ``` This mosaic displays can be read at several levels, corresponding to the successive splits of the tiles and the residual shading. Several trends are clear for viewers who persist: * Overall, there are about the same number of viewers on each weekday, with slightly more on Thursday. * Looking at time slots, viewership is slightly greater from 9:00 - 10:00 overall and also 8:00 - 9:00 on Thursday and Friday From the residual shading of the tiles: * Monday: CBS dominates in all time slots. * Tuesday" ABC and CBS dominate after 9:00 * Thursday: is a largely NBC day * Friday: ABC dominates in the early evening <!-- ```{r, tv4} --> <!-- TV.df <- as.data.frame.table(TV) --> <!-- levels(TV.df$Time) <- c(rep("8:00-8:59",4), --> <!-- rep("9:00-9:59",4), --> <!-- rep("10:00-10:44",3)) --> <!-- TV3 <- xtabs(Freq ~ Day + Time + Network, TV.df) --> <!-- structable(Day ~ Time+Network, TV3) --> <!-- ``` --> <!-- Whew! See \figref{fig:TV-mosaic} for a mosaic plot of the `TV3` data. --> <!-- The table is too large to display conveniently, but we can show a subtable --> <!-- by selecting the indices. This call to `ftable()` subsets the first three --> <!-- levels of each factor. --> <!-- ```{r tv4} --> <!-- ftable(TV[1:3,1:3,1:3,1:3], col.vars = 3:4) --> <!-- ``` --> <!-- We've come this far, so we might as well show a mosaic display. This is analogous to that used by --> <!-- @vcd:Hartigan+Kleiner:1984. The result is too complex to see very much. It would be useful to simplify --> <!-- the table by collapsing one or more of the table dimensions, e.g., `Time`. --> <!-- ```{r tv-mosaic2, fig.height=7, fig.width=7} --> <!-- mosaic(TV[,,1:4,], shade=TRUE, --> <!-- labeling_args = list(abbreviate_labs = c(8,5,1,1))) --> <!-- ``` --> # References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/vignettes/creating.Rmd
--- title: "Datasets for categorical data analysis" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Datasets for categorical data analysis} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/datasets-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") ``` The `vcdExtra` package contains `r nrow(vcdExtra::datasets("vcdExtra"))` datasets, taken from the literature on categorical data analysis, and selected to illustrate various methods of analysis and data display. These are in addition to the `r nrow(vcdExtra::datasets("vcd"))` datasets in the [vcd package](https://cran.r-project.org/package=vcd). To make it easier to find those which illustrate a particular method, the datasets in `vcdExtra` have been classified using method tags. This vignette creates an "inverse table", listing the datasets that apply to each method. It also illustrates a general method for classifying datasets in R packages. ```{r load} library(dplyr) library(tidyr) library(readxl) ``` ## Processing tags Using the result of `vcdExtra::datasets(package="vcdExtra")` I created a spreadsheet, `vcdExtra-datasets.xlsx`, and then added method tags. ```{r read-datasets} dsets_tagged <- read_excel(here::here("inst", "extdata", "vcdExtra-datasets.xlsx"), sheet="vcdExtra-datasets") dsets_tagged <- dsets_tagged |> dplyr::select(-Title, -dim) |> dplyr::rename(dataset = Item) head(dsets_tagged) ``` To invert the table, need to split tags into separate observations, then collapse the rows for the same tag. ```{r split-tags} dset_split <- dsets_tagged |> tidyr::separate_longer_delim(tags, delim = ";") |> dplyr::mutate(tag = stringr::str_trim(tags)) |> dplyr::select(-tags) #' ## collapse the rows for the same tag tag_dset <- dset_split |> arrange(tag) |> dplyr::group_by(tag) |> dplyr::summarise(datasets = paste(dataset, collapse = "; ")) |> ungroup() # get a list of the unique tags unique(tag_dset$tag) ``` ## Make this into a nice table Another sheet in the spreadsheet gives a more descriptive `topic` for corresponding to each tag. ```{r read-tags} tags <- read_excel(here::here("inst", "extdata", "vcdExtra-datasets.xlsx"), sheet="tags") head(tags) ``` Now, join this with the `tag_dset` created above. ```{r join-tags} tag_dset <- tag_dset |> dplyr::left_join(tags, by = "tag") |> dplyr::relocate(topic, .after = tag) tag_dset |> dplyr::select(-tag) |> head() ``` ### Add links to `help()` We're almost there. It would be nice if the dataset names could be linked to their documentation. This function is designed to work with the `pkgdown` site. There are different ways this can be done, but what seems to work is a link to `../reference/{dataset}.html` Unfortunately, this won't work in the actual vignette. ```{r add-links} add_links <- function(dsets, style = c("reference", "help", "rdrr.io"), sep = "; ") { style <- match.arg(style) names <- stringr::str_split_1(dsets, sep) names <- dplyr::case_when( style == "help" ~ glue::glue("[{names}](help({names}))"), style == "reference" ~ glue::glue("[{names}](../reference/{names}.html)"), style == "rdrr.io" ~ glue::glue("[{names}](https://rdrr.io/cran/vcdExtra/man/{names}.html)") ) glue::glue_collapse(names, sep = sep) } ``` ## Make the table {#table} Use `purrr::map()` to apply `add_links()` to all the datasets for each tag. (`mutate(datasets = add_links(datasets))` by itself doesn't work.) ```{r kable} tag_dset |> dplyr::select(-tag) |> dplyr::mutate(datasets = purrr::map(datasets, add_links)) |> knitr::kable() ``` Voila!
/scratch/gouwar.j/cran-all/cranData/vcdExtra/vignettes/datasets.Rmd
--- title: "Demo - Housing Data" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Demo - Housing Data} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/demo-housing-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # colorize text colorize <- function(x, color) { if (knitr::is_latex_output()) { sprintf("\\textcolor{%s}{%s}", color, x) } else if (knitr::is_html_output()) { sprintf("<span style='color: %s;'>%s</span>", color, x) } else x } ``` This vignette was one of a series of `demo()` files in the package. It is still there as `demo("housing")`, but is now presented here with additional commentary and analysis, designed to highlight some aspects of analysis of categorical data and graphical display. ## Load packages I'll use the following packages in this vignette. ```{r} library(vcdExtra) library(MASS) library(effects) ``` ## Housing data The content here is the dataset `MASS::housing`, giving a 4-way, $3 \times 3 \times 4 \times 2$ frequency table of 1681 individuals from the *Copenhagen Housing Conditions Survey*, classified by their: * Satisfaction (`Sat`) with their housing circumstances (low, medium or high), * `Type` of rental dwelling (Tower, Apartment, Atrium or Terrace) * perceived influence (`Infl`) on management of the property (low, medium, high), and * degree of contact (`Cont`) with other residents (low or high) Load the data: ```{r housing} data(housing, package="MASS") str(housing) ``` ### Variables, levels and models Satisfaction (`Sat`) of these householders with their present housing circumstances is the **outcome variable** here. For purposes of analysis, note that `Sat` is an ordered factor with levels `"Low" < "Medium" < "High"`. Note also that Influence, with the same levels is just a "Factor", not an ordered one. I consider here just models using `glm(..., family=poisson)` or the equivalent in `MASS::loglm()`. The ordering of factor levels is important in graphical displays. We don't want to see them ordered alphabetically, "High", "Low", "Medium". The `housing` data.frame was constructed so that the levels of `Sat` and `Infl` appear in the dataset in their appropriate order. ```{r} levels(housing$Sat) levels(housing$Infl) ``` Other models, e.g., the **proportional odds** model, fit using `MASS:polr()` can take the ordinal nature of satisfaction into account. In `glm()` one could re-assign `Infl` as an ordered factor and examine linear vs. non-linear associations for this factor. But I don't do this here. ## Null model The most ignorant model asserts that all the table factors are mutually independent. In symbolic notation, this is `[S] [I] [T] [C]` where all terms in separate `[ ]` are supposed to be independent. This is `Freq ~ Sat + Infl + Type + Cont` as a formula for `glm()`. ```{r house.null} house.null <- glm(Freq ~ Sat + Infl + Type + Cont, family = poisson, data = housing) ``` ## Baseline model When `Sat` is the outcome variable, a minimal **baseline model** should allow for all associations among the predictors, symbolized as `[S] [I T C]`. That is, Influence, Type and Contact may be associated in arbitrary ways, just as multiple predictors can be correlated in regression models. In this framework, what remains to be explained is whether/how `Sat` depends on the combinations of the other variables. The baseline model therefore includes the full three-way term for the predictors. ```{r house.glm0} house.glm0 <- glm(Freq ~ Sat + Infl*Type*Cont, family = poisson, data = housing) ``` Both of these models fit terribly, but we can always use `anova(mod1, mod2,...)` to compare the *relative* fits of **nested** models. ```{r anova} anova(house.null, house.glm0, test = "Chisq") ``` ## Visualising model fit The baseline model is shown in the mosaic plot below. Note that this is applied not to the `housing` data, but rather to the `house.glm0` object (of class `glm`) resulting to a call to `vcdExtra::mosaic.glm()`. With four variables in the mosaic, labeling of the variable names and factor levels is a bit tricky, because labels must appear on all four sides of the plot. The `labeling_args` argument can be used to set more informative variable names and abbreviate factor levels where necessary. ```{r} #| label= mosaic-glm0a, #| warning = TRUE # labeling_args for mosaic() largs <- list(set_varnames = c( Infl="Influence on management", Cont="Contact among residents", Type="Type of dwelling", Sat="Satisfaction"), abbreviate=c(Type=3)) mosaic(house.glm0, labeling_args=largs, main='Baseline model: [ITC][Sat]') ``` In this plot we can see largish `r colorize("positive residuals", "blue")` in the blocks corresponding to (low satisfaction, low influence) and (high satisfaction, high influence) and clusters of largish `r colorize("negative residuals", "red")` in the opposite corners. By default, variables are used in the mosaic display in their order in the data table or frequency data.frame. The `r colorize("warning", "red")` reminds us that the order of conditioning used is `~Sat + Infl + Type + Cont`. ### Ordering the variables in the mosaic For `mosaic.glm()`, the conditioning order of variables in the mosaic can be set using the `formula` argument. Here, I rearrange the variables to put `Sat` as the last variable in the splitting / conditioning sequence. I also use `vcdExtra::modFit()` to add the LR $G^2$ fit statistic to the plot title. ```{r mosaic-glm0b} mosaic(house.glm0, formula = ~ Type + Infl + Cont + Sat, labeling_args=largs, main=paste('Baseline model: [ITC][Sat],', modFit(house.glm0)) ) ``` ## Adding association terms Clearly, satisfaction depends on one or more of the predictors, `Infl`, `Type` and `Cont` and possibly their interactions. As a first step it is useful to consider sequentially adding the association terms `Infl:Sat`, `Type:Sat`, `Cont:Sat` one at a time. This analysis is carried out using `MASS::addterm()`. ```{r addterm} MASS::addterm(house.glm0, ~ . + Sat:(Infl + Type + Cont), test = "Chisq") ``` Based on this, it is useful to consider a "main-effects" model for satisfaction, adding all three two-way terms involving satisfaction. The `update()` method provides an easy way to add (or subtract) terms from a fitted model object. In the model formula, `.` stands for whatever was on the left side (`Freq`) or on the right side (`Sat + Infl*Type*Cont`) of the model (`house.glm0`) that is being updated. ```{r house-glm1} house.glm1 <- update(house.glm0, . ~ . + Sat*(Infl + Type + Cont)) ``` For comparison, we note that the same model can be fit using the iterative proportional scaling algorithm of `MASS::loglm()`. ```{r house-loglm1} (house.loglm1 <- MASS::loglm(Freq ~ Infl * Type * Cont + Sat*(Infl + Type + Cont), data = housing)) ``` ## Did the model get better? As before, `anova()` tests the added contribution of each more complex model over the one before. The residual deviance $G^2$ has been reduced from $G^2 (46) = 217.46$ for the baseline model `house.glm0` to $G^2 (34) = 38.66$ for the revised model `house.glm1`. The difference, $G^2(M1 | M0) = G^2 (12) = 178.79$ tests the collective additional fit provided by the two-way association of satisfaction with the predictors. ```{r} anova(house.glm0, house.glm1, test="Chisq") ``` ## Visualize model `glm1` The model `house.glm1` fits reasonably well, `r modFit(house.glm1)`, so most residuals are small. In the mosaic below, I use `gp=shading_Friendly` to shade the tiles so that positive and negative residuals are distinguished by color, and they are filled when the absolute value of the residual is outside $\pm 2, 4$. ```{r mosaic-glm1} mosaic(house.glm1, labeling_args=largs, main=paste('Model [IS][TS][CS],', modFit(house.glm1) ), gp=shading_Friendly) ``` One cell is highlighted here: The combination of medium influence, low contact and tower type, is more likely to give low satisfaction than the model predicts. Is this just an outlier, or is there something that can be interpreted and perhaps improve the model fit? It is hard tell, but the virtues of mosaic displays are that they help to: * diagnose overall patterns of associations, * spot unusual cells in relation to lack of fit of a given model. ## Can we drop any terms? When we add terms using `MASS::addterm()`, they are added sequentially. It might be the case that once some term is added, a previously added term is no longer important. Running `MASS::dropterm()` on the `housel.glm1` model checks for this. ```{r dropterm} MASS::dropterm(house.glm1, test = "Chisq") ``` Note that the three-way term `Infl:Type:Cont` is not significant. However, with `Sat` as the response, the associations of all predictors must be included in the model. ## What about two-way interactions? The model so far says that each of influence, type and control have separate, additive effects on the level of satisfaction, what I called a "main-effects" model. It might be the case that some of the predictors have *interaction* effects, e.g., that the effect of influence on satisfaction might vary with the type of dwelling or the level of control. An easy way to test for these is to update the main-effects model, adding all possible two-way interactions for `Sat`, one at a time, with `addterm()`. ```{r addterm1} MASS::addterm(house.glm1, ~. + Sat:(Infl + Type + Cont)^2, test = "Chisq") ``` The result shows that adding the term `Infl:Type:Sat` reduces the deviance $G^2$ from 38.66 to 16.11. The difference, $G^2(M1 + ITS | M1) = G^2 (12) = 22.55$ reflects a substantial improvement. The remaining two-way interaction terms reduce the deviance by smaller and non-significant amounts, relative to `house.glm1`. Model fitting should be guided by substance, not just statistical machinery. Nonetheless, it seems arguably sensible to add one two-way term to the model, giving `house.glm2`. ```{r} house.glm2 <- update(house.glm1, . ~ . + Sat:Infl:Type) ``` ## Model parsimony: AIC & BIC Adding more association terms to a model will always improve it. The question is, whether that is "worth it"? "Worth it" concerns the trade-off between model fit and parsimony. Sometimes we might prefer a model with fewer parameters to one that has a slightly better fit, but requires more model terms and parameters. The AIC and BIC statistics are designed to adjust our assessment of model fit by penalizing it for using more parameters. Equivalently, they deduct from the likelihood ratio $G^2$ a term proportional to the residual $\text{df}$ of the model. In any case -- **smaller is better** for both AIC and BIC. $$AIC = G^2 - 2 \: \text{df}$$ $$BIC = G^2 - \log(n) \: \text{df}$$ These measures are provided by `AIC()`, `BIC()`, and can be used to compare models using `vcdExtra::LRstats()`. ```{r lrstats} LRstats(house.glm0, house.glm1, house.glm2) ``` By these metrics, model `house.glm1` is best on both AIC and BIC. The increased goodness-of-fit (smaller $G^2$) of model `house.glm2` is not worth the extra cost of parameters in the `house.glm2` model. <!-- ## Effect plots --> <!-- ```{r} --> <!-- house.eff <-allEffects(house.glm1) --> <!-- ``` -->
/scratch/gouwar.j/cran-all/cranData/vcdExtra/vignettes/demo-housing.Rmd
--- title: "Loglinear Models" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Loglinear Models} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/tut03-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # preload datasets ??? set.seed(1071) library(vcd) library(vcdExtra) library(ggplot2) data(HairEyeColor) data(PreSex) data(Arthritis, package="vcd") art <- xtabs(~Treatment + Improved, data = Arthritis) if(!file.exists("fig")) dir.create("fig") ``` You can use the `loglm()` function in the `MASS` package to fit log-linear models. Equivalent models can also be fit (from a different perspective) as generalized linear models with the `glm()` function using the `family='poisson'` argument, and the `gnm` package provides a wider range of generalized *nonlinear* models, particularly for testing structured associations. The visualization methods for these models were originally developed for models fit using `loglm()`, so this approach is emphasized here. Some extensions of these methods for models fit using `glm()` and `gnm()` are contained in the `vcdExtra` package and illustrated in @ref(sec:glm). Assume we have a 3-way contingency table based on variables A, B, and C. The possible different forms of loglinear models for a 3-way table are shown in the table below. \@(tab:loglin-3way) The **Model formula** column shows how to express each model for `loglm()` in R. ^[For `glm()`, or `gnm()`, with the data in the form of a frequency data.frame, the same model is specified in the form `glm(Freq` $\sim$ `..., family="poisson")`, where `Freq` is the name of the cell frequency variable and `...` specifies the *Model formula*.] In the **Interpretation** column, the symbol "$\perp$" is to be read as "is independent of," and "$\;|\;$" means "conditional on," or "adjusting for," or just "given". | **Model** | **Model formula** | **Symbol** | **Interpretation** | |:-------------------------|:-------------------|:---------------|:-----------------------| | Mutual independence | `~A + B + C` | $[A][B][C]$ | $A \perp B \perp C$ | | Joint independence | `~A*B + C` | $[AB][C]$ | $(A \: B) \perp C$ | | Conditional independence | `~(A+B)*C` | $[AC][BC]$ | $(A \perp B) \;|\; C$ | | All two-way associations | `~A*B + A*C + B*C` | $[AB][AC][BC]$ | homogeneous association| | Saturated model | `~A*B*C` | $[ABC]$ | 3-way association | For example, the formula `~A + B + C` specifies the model of *mutual independence* with no associations among the three factors. In standard notation for the expected frequencies $m_{ijk}$, this corresponds to $$ \log ( m_{ijk} ) = \mu + \lambda_i^A + \lambda_j^B + \lambda_k^C \equiv A + B + C $$ The parameters $\lambda_i^A , \lambda_j^B$ and $\lambda_k^C$ pertain to the differences among the one-way marginal frequencies for the factors A, B and C. Similarly, the model of *joint independence*, $(A \: B) \perp C$, allows an association between A and B, but specifies that C is independent of both of these and their combinations, $$ \log ( m_{ijk} ) = \mu + \lambda_i^A + \lambda_j^B + \lambda_k^C + \lambda_{ij}^{AB} \equiv A * B + C $$ where the parameters $\lambda_{ij}^{AB}$ pertain to the overall association between A and B (collapsing over C). In the literature or text books, you will often find these models expressed in shorthand symbolic notation, using brackets, `[ ]` to enclose the *high-order terms* in the model. Thus, the joint independence model can be denoted `[AB][C]`, as shown in the **Symbol** column in the table. \@(tab:loglin-3way). Models of *conditional independence* allow (and fit) two of the three possible two-way associations. There are three such models, depending on which variable is conditioned upon. For a given conditional independence model, e.g., `[AB][AC]`, the given variable is the one common to all terms, so this example has the interpretation $(B \perp C) \;|\; A$. ## Fitting with `loglm()` {#sec:loglm} For example, we can fit the model of mutual independence among hair color, eye color and sex in `HairEyeColor` as ```{r, loglm-hec1} library(MASS) ## Independence model of hair and eye color and sex. hec.1 <- loglm(~Hair+Eye+Sex, data=HairEyeColor) hec.1 ``` Similarly, the models of conditional independence and joint independence are specified as ```{r, loglm-hec2} ## Conditional independence hec.2 <- loglm(~(Hair + Eye) * Sex, data=HairEyeColor) hec.2 ``` ```{r, loglm-hec3} ## Joint independence model. hec.3 <- loglm(~Hair*Eye + Sex, data=HairEyeColor) hec.3 ``` Note that printing the model gives a brief summary of the goodness of fit. A set of models can be compared using the `anova()` function. ```{r, loglm-anova} anova(hec.1, hec.2, hec.3) ``` ## Fitting with `glm()` and `gnm()` {#sec:glm} The `glm()` approach, and extensions of this in the `gnm` package allows a much wider class of models for frequency data to be fit than can be handled by `loglm()`. Of particular importance are models for ordinal factors and for square tables, where we can test more structured hypotheses about the patterns of association than are provided in the tests of general association under `loglm()`. These are similar in spirit to the non-parametric CMH tests described in \@ref(sec:CMH). ***Example***: The data `Mental` in the `vcdExtra` package gives a two-way table in frequency form classifying young people by their mental health status and parents' socioeconomic status (SES), where both of these variables are ordered factors. ```{r, mental1} data(Mental, package = "vcdExtra") str(Mental) xtabs(Freq ~ mental + ses, data=Mental) # display the frequency table ``` Simple ways of handling ordinal variables involve assigning scores to the table categories, and the simplest cases are to use integer scores, either for the row variable (``column effects'' model), the column variable (``row effects'' model), or both (``uniform association'' model). ```{r, mental2} indep <- glm(Freq ~ mental + ses, family = poisson, data = Mental) # independence model ``` To fit more parsimonious models than general association, we can define numeric scores for the row and column categories ```{r, mental3} # Use integer scores for rows/cols Cscore <- as.numeric(Mental$ses) Rscore <- as.numeric(Mental$mental) ``` Then, the row effects model, the column effects model, and the uniform association model can be fit as follows. The essential idea is to replace a factor variable with its numeric equivalent in the model formula for the association term. ```{r, mental4} # column effects model (ses) coleff <- glm(Freq ~ mental + ses + Rscore:ses, family = poisson, data = Mental) # row effects model (mental) roweff <- glm(Freq ~ mental + ses + mental:Cscore, family = poisson, data = Mental) # linear x linear association linlin <- glm(Freq ~ mental + ses + Rscore:Cscore, family = poisson, data = Mental) ``` The `LRstats()` function in `vcdExtra` provides a nice, compact summary of the fit statistics for a set of models, collected into a *glmlist* object. Smaller is better for AIC and BIC. ```{r, mental4a} # compare models using AIC, BIC, etc vcdExtra::LRstats(glmlist(indep, roweff, coleff, linlin)) ``` For specific model comparisons, we can also carry out tests of *nested* models with `anova()` when those models are listed from smallest to largest. Here, there are two separate paths from the most restrictive (independence) model through the model of uniform association, to those that allow only one of row effects or column effects. ```{r, mental5} anova(indep, linlin, coleff, test="Chisq") anova(indep, linlin, roweff, test="Chisq") ``` The model of linear by linear association seems best on all accounts. For comparison, one might try the CMH tests on these data: ```{r, mental6} CMHtest(xtabs(Freq~ses+mental, data=Mental)) ``` ## Non-linear terms The strength of the `gnm` package is that it handles a wide variety of models that handle non-linear terms, where the parameters enter the model beyond a simple linear function. The simplest example is the Goodman RC(1) model [@Goodman:79], which allows a multiplicative term to account for the association of the table variables. In the notation of generalized linear models with a log link, this can be expressed as $$ \log \mu_{ij} = \alpha_i + \beta_j + \gamma_{i} \delta_{j} ,$$ where the row-multiplicative effect parameters $\gamma_i$ and corresponding column parameters $\delta_j$ are estimated from the data.% ^[This is similar in spirit to a correspondence analysis with a single dimension, but as a statistical model.] Similarly, the RC(2) model adds two multiplicative terms to the independence model, $$ \log \mu_{ij} = \alpha_i + \beta_j + \gamma_{i1} \delta_{j1} + \gamma_{i2} \delta_{j2} . $$ In the `gnm` package, these models may be fit using the `Mult()` to specify the multiplicative term, and `instances()` to specify several such terms. ***Example***: For the `Mental` data, we fit the RC(1) and RC(2) models, and compare these with the independence model. ```{r, mental7} RC1 <- gnm(Freq ~ mental + ses + Mult(mental,ses), data=Mental, family=poisson, verbose=FALSE) RC2 <- gnm(Freq ~ mental+ses + instances(Mult(mental,ses),2), data=Mental, family=poisson, verbose=FALSE) anova(indep, RC1, RC2, test="Chisq") ``` ## References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/vignettes/loglinear.Rmd
--- title: "Mobility tables" author: "Michael Friendly" date: "`r Sys.Date()`" package: vcdExtra output: rmarkdown::html_vignette: fig_caption: yes bibliography: ["vcd.bib", "vcdExtra.bib", "vignettes.bib"] csl: apa.csl vignette: > %\VignetteIndexEntry{Mobility tables} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, message = FALSE, warning = FALSE, fig.height = 6, fig.width = 7, fig.path = "fig/mobility-", dev = "png", comment = "##" ) # save some typing knitr::set_alias(w = "fig.width", h = "fig.height", cap = "fig.cap") # colorize text colorize <- function(x, color) { if (knitr::is_latex_output()) { sprintf("\\textcolor{%s}{%s}", color, x) } else if (knitr::is_html_output()) { sprintf("<span style='color: %s;'>%s</span>", color, x) } else x } ``` ## Social mobility Social mobility is an important concept in sociology, and its' study has led to a wide range of developments in categorical data analysis in what are often called _mobility tables_. The idea is to study the movement of individuals, families, households or other categories of people within or between social strata in a society, across time or space. This refers to a change in social status relative to one's current social location within a given society. Using survey data, the most frequent examples relate to changes in income or wealth, but most often this is studied via classification in occupational categories ("professional, "managerial", "skilled manual", ...). Most often this is studied _intergenerationaly_ using the occupational categories of fathers and sons. Mobility tables are nearly always _square_ tables, with the same categories for the row and column variables. As such, they nearly always exhibit positive associations along the diagonal cells. What is of interest are specialized models, intermediate between the null model of independence and the saturated model. ### Models These models include important special cases: - **quasi-independence**: Ignoring diagonal cells, are the row and column variables independent? - **symmetry**: Are associations above the diagonal equal to the corresponding ones below the diagonal? - **row effects, col effects, linear x linear**: Typically, the factors in such tables are ordinal. To what extent can the models be simplified by assigning integer scores to the row, column categories or both? - **multiplicative RC**: RC models attempt to estimate the scores for the row and column categories. - **topographical models**: It is possible that the associations among occupational categories exhibit consistent patterns according to their nature. These models allow specifying a theoretically interesting pattern. - **crossings models**: assert that there are different difficulty parameters for crossing from category to the next and associations between categories decrease with their separation. While standard loglinear models can be fit using `MASS::loglm`, these models require use of ``stats::glm()` or `gnm::gnm()`, as I illustrate below. ## Hauser data This vignette uses the `vcdExtra::Hauser79` dataset, a cross-classification of 19,912 individuals by father's occupation and son's first occupation for U.S. men aged 20-64 in 1973. The data comes from @Hauser:79 and has been also analysed by @PowersXie:2008. The discussion draws on @FriendlyMeyer:2016:DDAR, Ch. 10. ```{r hauser-data} data("Hauser79", package="vcdExtra") str(Hauser79) (Hauser_tab <- xtabs(Freq ~ Father + Son, data=Hauser79)) ``` As can be seen, `Hauser79` is a data.frame in frequency form. The factor levels in this table are a coarse grouping of occupational categories, so: - `UpNM` = professional and kindred workers, managers and officials, and non-retail sales workers; - `LoNM` = proprietors, clerical and kindred workers, and retail sales workers; - `UpM` = craftsmen, foremen, and kindred workers; - `LoM` = service workers, operatives and kindred workers, and laborers (except farm); - `Farm` = farmers and farm managers, farm laborers, and foremen. ### Load packages ```{r load} library(vcdExtra) library(gnm) library(dplyr) ``` ### Mosaic plots `Hauser_tab` is a `table` object, and the simplest plot for the frequencies is the default `plot()` method, giving a `graphics::mosaicplot()`. ```{r mosaicplot} plot(Hauser_tab, shade=TRUE) ``` The frequencies are first split according to father's occupational category (the first table dimension) and then by sons' occupation. The most common category for fathers is lower manual, followed by farm. `mosaicplot()`, using `shade=TRUE` colors the tiles according to the sign and magnitude of the residuals from an independence model: shades of `r colorize("positive", "blue")` for positive residuals and `r colorize("negative", "red")` red for negative residuals. `vcd::mosaic()` gives a similar display, but is much more flexible in the labeling of the row and column variable, labels for the categories, and the scheme used for shading the tiles. Here, I simply assign longer labels for the row and column variables, using the `labeling_args` argument to `mosaic()`. ```{r mosaic1} labels <- list(set_varnames = c(Father="Father's occupation", Son="Son's occupation")) mosaic(Freq ~ Father + Son, data=Hauser79, labeling_args = labels, shade=TRUE, legend = FALSE) ``` ### Fitting and graphing models The call to `vcd::mosaic()` above takes the `Hauser79` dataset as input. Internally, it fits the model of independence and displays the result, but for more complex tables, control of the fitted model is limited. Unlike `mosaicplot()` and even the [`ggmosaic`]( https://CRAN.R-project.org/package=ggmosaic) package, `vcdExtra::mosaic.glm()` is a `mosaic` **method** for `glm` objects. This means you can fit any model, and supply the model object to `mosaic()`. (Note that in `mosaic()`, the `formula` argument determines the order of splitting in the mosaic, not a loglinear formula.) ```{r indep} hauser.indep <- glm(Freq ~ Father + Son, data=Hauser79, family=poisson) # the same mosaic, using the fitted model mosaic(hauser.indep, formula = ~ Father + Son, labeling_args = labels, legend = FALSE, main="Independence model") ``` ## Quasi-independence Among the most important advances from the social mobility literature is the idea that associations between row and column variables in square tables can be explored in greater depth if we ignore the obvious association in the diagonal cells. The result is a model of _quasi-independence_, asserting that fathers' and sons' occupations are independent, ignoring the diagonal cells. For a two-way table, quasi-independence can be expressed as $$ \pi_{ij} = \pi_{i+} \pi_{+j} \quad\quad \mbox{for } i\ne j $$ or in loglinear form as: $$ \log m_{ij} = \mu + \lambda_i^A + \lambda_j^B + \delta_i I(i=j) \quad . $$ This model effectively adds one parameter, $\delta_i$, for each main diagonal cell and fits those frequencies perfectly. In the [`gnm`]( https://CRAN.R-project.org/package=gnm) package, `gnm::Diag()` creates the appropriate term in the model formula, using a symbol in the diagonal cells and "." otherwise. ```{r Diag} # with symbols with(Hauser79, Diag(Father, Son)) |> matrix(nrow=5) ``` We proceed to fit and plot the quasi-independence model by updating the independence model, adding the term `Diag(Father, Son)`. ```{r quasi} hauser.quasi <- update(hauser.indep, ~ . + Diag(Father, Son)) mosaic(hauser.quasi, ~ Father+Son, labeling_args = labels, legend = FALSE, main="Quasi-independence model") ``` Note that the pattern of residuals shows a systematic pattern of `r colorize("positive", "blue")` and `r colorize("negative", "red")` residuals above and below the diagonal tiles. We turn to this next. ### Symmetry and quasi-symmetry Another advance from the social mobility literature was the idea of how to test for _differences_ in occupational categories between fathers and sons. The null hypothesis of no systematic differences can be formulated as a test of **symmetry** in the table, $$ \pi_{ij} = \pi_{ji} \quad\quad \mbox{for } i\ne j \quad , $$ which asserts that sons are as likely to move from their father's occupation $i$ to another category $j$ as they were to move in the reverse direction, $j$ to $i$. An alternative, "Upward mobility", i.e., that sons who did not stay in their father's occupational category moved to a higher category on average would mean that $$ \pi_{ij} < \pi_{ji} \quad\quad \mbox{for } i\ne j $$ Yet this model is overly strong, because it also asserts **marginal homogeneity**, that the marginal probabilities of row and column values are equal, $\pi_{i+} = \pi_{+i}$ for all $i$. Consequently, this hypothesis is most often tested as a model for **quasi-symmetry**, that also ignores the diagonal cells. Symmetry is modeled by the function `gnm::Symm()`. It returns a factor with the same labels for positions above and below the diagonal. ```{r symm} with(Hauser79, Symm(Father, Son)) |> matrix(nrow=5) ``` To fit the model of quasi-symmetry, add both `Diag()` and `Symm()` to the model of independence. ```{r qsymm} hauser.qsymm <- update(hauser.indep, ~ . + Diag(Father,Son) + Symm(Father,Son)) ``` To compare the models so far, we can use `anova()` or `vcdExtra::LRstats(): ```{r anova1} anova(hauser.indep, hauser.quasi, hauser.qsymm, test="Chisq") LRstats(hauser.indep, hauser.quasi, hauser.qsymm) ``` This `hauser.qsymm` model represents a huge improvement in goodness of fit. With such a large sample size, it might be considered an acceptable fit. But, this model of quasi-symmetry still shows some residual lack of fit. To visualize this in the mosaic, we can label the cells with their standardized residuals. ```{r qsymm-mosaic} mosaic(hauser.qsymm, ~ Father+Son, labeling_args = labels, labeling = labeling_residuals, residuals_type ="rstandard", legend = FALSE, main="Quasi-symmetry model") ``` The cells with the largest lack of symmetry (using standardized residuals) are those for the upper and lower non-manual occupations, where the son of an upper manual worker is less likely to move to lower non-manual work than the reverse. ### Topological models It is also possible that there are more subtle patterns of association one might want to model, with specific parameters for particular combinations of the occupational categories (beyond the idea of symmetry). @Hauser:79 developed this idea in what are now called **topological** models or **levels** models, where an arbitrary pattern of associations can be specified, implemented in `gnm::Topo()`. ```{r topo-levels} # Levels for Hauser 5-level model levels <- matrix(c( 2, 4, 5, 5, 5, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 4, 4, 5, 5, 5, 4, 1), nrow = 5, ncol = 5, byrow=TRUE) ``` ```{r topo-mosaic} hauser.topo <- update(hauser.indep, ~ . + Topo(Father, Son, spec=levels)) mosaic(hauser.topo, ~Father+Son, labeling_args = labels, labeling = labeling_residuals, residuals_type ="rstandard", legend = FALSE, main="Topological model") ``` Comparing models, we can see that the model of quasi-symmetry is the best so far, using AIC as the measure: ```{r} LRstats(hauser.indep, hauser.quasi, hauser.qsymm, hauser.topo, sortby = "AIC") ``` ## Ordinal tables Because the factors in mobility tables are ordered, another path to simplifying the saturated model is to consider assigning numerical scores (typically consecutive integers) to the categories. When both variables are assigned scores, this gives the **linear-by-linear model**, $$ \log ( m_{ij} ) = \mu + \lambda_i^A + \lambda_j^B + \gamma \: a_i b_j \quad , $$ where $a_i$ and $b_j$ are the row and column numeric scores. This model is also called the model of **uniform association** [@Goodman:79] because, for integer scores, $a_i=i$, $b_j=j$, this model has only one extra parameter, $\gamma$, which is the common odds local ratio. The independence model is the special case, $\gamma=0$. In contrast, the saturated model, allowing general association $\lambda_{ij}^{AB}$, uses $(I-1)(J-1)$ additional parameters. For square tables, like mobility tables, this model can be amended to include a diagonal term, `Diag()` ```{r scores} Sscore <- as.numeric(Hauser79$Son) Fscore <- as.numeric(Hauser79$Father) Hauser79 |> cbind(Fscore, Fscore) |> head() ``` To fit this model, I use `Fscore * Sscore` for the linear x linear association and add `Diag(Father, Son)` to fit the diagonal cells exactly. ```{r hauser-UAdiag} hauser.UAdiag <- update(hauser.indep, . ~ . + Fscore : Sscore + Diag(Father, Son)) LRstats(hauser.UAdiag) ``` In this model, the estimated common local log odds ratio---the coefficient $\gamma$ for the linear-by-linear term `Fscore:Sscore`, is given by: ```{r} coef(hauser.UAdiag)[["Fscore:Sscore"]] ``` For comparisons not involving the diagonal cells, each step down the scale of occupational categories for the father multiplies the odds that the son will also be in one lower category by $\exp (0.158) = 1.172$, an increase of 17%. But this model does not seem to be any improvement over quasi-symmetry. From the pattern of residuals in the mosaic, we see a number of large residuals of various signs in the lower triangular, where the son's occupation is of a higher level than that of the father. ```{r UAdiag-mosaic} mosaic(hauser.UAdiag, ~ Father+Son, labeling_args = labels, labeling = labeling_residuals, residuals_type ="rstandard", legend = FALSE, main="Uniform association + Diag()") ``` ## Model comparison plots Finally, for comparing a largish collection of models, a model comparison plot can show the trade-off between goodness-of-fit and parsimony by plotting measures like $G^2/df$, AIC, or BIC against degrees of freedom. The plot below, including quite a few more models, uses a log scale for BIC to emphasize differences among better fitting models. (The code for this plot is shown on p. 399 of @FriendlyMeyer:2016:DDAR). ![](fig/hauser-model-plot.png){width=80%} ## References
/scratch/gouwar.j/cran-all/cranData/vcdExtra/vignettes/mobility.Rmd