content
stringlengths
0
14.9M
filename
stringlengths
44
136
`eventstar` <- function(x, qmax=5) { if (is.null(dim(x))) x <- matrix(x, 1, length(x)) else x <- as.matrix(x) # faster than data.frame lossfun <- function(q, x) tsallis(x, scales=q, norm=TRUE) qstarfun <- function(x) { optimize(lossfun, interval=c(0, qmax), x=x)$minimum } qs <- apply(x, 1, qstarfun) Hs <- sapply(1:nrow(x), function(i) tsallis(x[i,], scales=qs[i], hill=FALSE)) S <- rowSums(x) Es <- ifelse(qs==1, log(S), Hs/((S^(1-qs)-1)/(1-qs))) Ds <- (1-(qs-1)*Hs)^(1/(1-qs)) out <- data.frame(qstar=qs, Estar=Es, Hstar=Hs, Dstar=Ds) rownames(out) <- rownames(x) out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/eventstar.R
`extractAIC.cca` <- function (fit, scale = 0, k = 2, ...) { n <- nobs(fit) edf <- 1 if (!is.null(fit$CCA$rank)) edf <- edf + fit$CCA$qrank if (!is.null(fit$pCCA$QR)) edf <- edf + fit$pCCA$QR$rank #edf <- n - fit$CA$rank RSS <- deviance(fit) dev <- if(scale > 0) RSS/scale - n else n * log(RSS/n) c(edf, dev + k*edf) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/extractAIC.cca.R
`factorfit` <- function (X, P, permutations = 0, strata = NULL, w, ...) { EPS <- sqrt(.Machine$double.eps) P <- as.data.frame(P) ## Check that all variables are factors, and coerce if necessary if(any(!sapply(P, is.factor))) P <- data.frame(lapply(P, function(x) if (is.factor(x)) x else factor(x))) P <- droplevels(P, exclude = NA) ## make sure only the used levels are present if (any(!sapply(P, is.factor))) stop("all non-numeric variables must be factors") NR <- nrow(X) if (missing(w) || is.null(w)) w <- 1 if (length(w) == 1) w <- rep(w, NR) r <- NULL pval <- NULL totvar <- .Call(do_goffactor, X, rep(1L, NR), 1L, w) sol <- centroids.cca(X, P, w) var.id <- rep(names(P), sapply(P, nlevels)) ## make permutation matrix for all variables handled in the next loop permat <- getPermuteMatrix(permutations, NR, strata = strata) permutations <- nrow(permat) for (i in seq_along(P)) { A <- as.integer(P[[i]]) NL <- nlevels(P[[i]]) invar <- .Call(do_goffactor, X, A, NL, w) r.this <- 1 - invar/totvar r <- c(r, r.this) if (permutations) { A <- as.integer(P[[i]]) NL <- nlevels(P[[i]]) ptest <- function(indx, ...) { take <- A[indx] invar <- .Call(do_goffactor, X, take, NL, w) 1 - invar/totvar } tmp <- sapply(seq_len(permutations), function(indx,...) ptest(permat[indx,], ...)) pval.this <- (sum(tmp >= r.this - EPS) + 1)/(permutations + 1) pval <- c(pval, pval.this) } } if (is.null(colnames(X))) colnames(sol) <- paste("Dim", 1:ncol(sol), sep = "") else colnames(sol) <- colnames(X) names(r) <- names(P) if (!is.null(pval)) names(pval) <- names(P) out <- list(centroids = sol, r = r, permutations = permutations, pvals = pval, var.id = var.id) out$control <- attr(permat, "control") class(out) <- "factorfit" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/factorfit.R
`fieller.MOStest` <- function (object, level = 0.95) { smodel <- summary(object$mod) ## overdispersion included in cov.scaled var <- smodel$cov.scaled k <- coef(object$mod) b2 <- -2 * k[3] u <- -k[2]/2/k[3] alpha <- (1-level)/2 limits <- numeric(2) names(limits) <- paste(round(100*(c(alpha, 1-alpha)), 1), "%") wvar <- var[2,2] uvar <- 4 * var[3,3] vvar <- -2 * var[2,3] z <- qnorm(1 - alpha) g <- z^2 * uvar/b2^2 if (g >= 1) { limits <- c(NA, NA) } else { x <- u - g * vvar/uvar f <- z/b2 s <- sqrt(wvar - 2 * u * vvar + u^2 * uvar - g * (wvar - vvar^2/uvar)) limits[1] <- (x - f * s)/(1 - g) limits[2] <- (x + f * s)/(1 - g) } limits }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fieller.MOStest.R
`fisher.alpha` <- function (x, MARGIN = 1, ...) { x <- as.matrix(x) if(ncol(x) == 1) x <- t(x) sol <- apply(x, MARGIN, fisherfit) out <- unlist(lapply(sol, function(x) x$estimate)) if (FALSE) { out <- list(alpha = out) out$se <- unlist(lapply(sol, function(x) sqrt(diag(solve(x$hessian)))[1])) out$df.residual <- unlist(lapply(sol, df.residual)) out$code <- unlist(lapply(sol, function(x) x$code)) out <- as.data.frame(out) } out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fisher.alpha.R
## Fisher alpha is actually based only on the number of species S and ## number of individuals. `fisherfit` <- function(x, ...) { nr <- as.fisher(x) S <- sum(nr) N <- sum(x) ## Solve 'x' (Fisher alpha). d1fun <- function(x, S, N) x * log(1 + N/x) - S ## Function will give extremely high values when all species occur ## only once or S==N, starting from fisherfit(1) which is ca. 1e8, ## and it can make sense to have special treatment of S==N. With S ## == 0, we force alpha 0 whereas the function would give ## fisherfit(0) as 1 (which hardly makes sense). if (S > 0) { sol <- uniroot(d1fun, c(1,50), extendInt = "upX", S = S, N = N, ...) if (S == N) warning("all species singletons: alpha arbitrarily high") } else { sol <- list(root = 0, iter = 0, estim.prec = NA) } nuisance <- N/(N + sol$root) ## we used nlm() earlier, and the following output is compatible out <- list(estimate = sol$root, hessian = NA, iterations = sol$iter, df.residual = NA, nuisance = nuisance, fisher = nr, estim.prec = sol$estim.prec, code = 2*is.na(sol$estim.prec) + 1) class(out) <- "fisherfit" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fisherfit.R
fitspecaccum <- function(object, model, method = "random", ...) { MODELS <- c("arrhenius", "gleason", "gitay", "lomolino", "asymp", "gompertz", "michaelis-menten", "logis", "weibull") model <- match.arg(model, MODELS) if (!inherits(object, "specaccum")) object <- specaccum(object, method = method, ...) if (is.null(object$perm)) SpeciesRichness <- as.matrix(object$richness) else SpeciesRichness <- object$perm if (!is.null(object$individuals)) x <- object$individuals else x <- object$sites hasWeights <- !is.null(object$weights) ## scale weights to correspond to the no. of sites if (hasWeights) { w <- as.matrix(object$weights) n <- nrow(w) w <- sweep(w, 2, w[n,], "/") * n } NLSFUN <- function(y, x, model, ...) { switch(model, "arrhenius" = nls(y ~ SSarrhenius(x, k, z), ...), "gleason" = nls(y ~ SSgleason(x, k, slope), ...), "gitay" = nls(y ~ SSgitay(x, k, slope), ...), "lomolino" = nls(y ~ SSlomolino(x, Asym, xmid, slope), ...), "asymp" = nls(y ~ SSasymp(x, Asym, R0, lrc), ...), "gompertz" = nls(y ~ SSgompertz(x, Asym, xmid, scal), ...), "michaelis-menten" = nls(y ~ SSmicmen(x, Vm, K), ...), "logis" = nls(y ~ SSlogis(x, Asym, xmid, scal), ...), "weibull" = nls(y ~ SSweibull(x, Asym, Drop, lrc, par), ...)) } mods <- lapply(seq_len(NCOL(SpeciesRichness)), function(i, ...) NLSFUN(SpeciesRichness[,i], if (hasWeights) w[,i] else x, model, ...), ...) object$fitted <- drop(sapply(mods, fitted)) object$residuals <- drop(sapply(mods, residuals)) object$coefficients <- drop(sapply(mods, coef)) object$SSmodel <- model object$models <- mods object$call <- match.call() class(object) <- c("fitspecaccum", class(object)) object } ### plot function `plot.fitspecaccum` <- function(x, col = par("fg"), lty = 1, xlab = "Sites", ylab = x$method, ...) { if (is.null(x$weights)) fv <- fitted(x) else fv <- sapply(x$models, predict, newdata = list(x = x$sites)) matplot(x$sites, fv, col = col, lty = lty, pch = NA, xlab = xlab, ylab = ylab, type = "l", ...) invisible() } `lines.fitspecaccum` <- function(x, col = par("fg"), lty = 1, ...) { if (is.null(x$weights)) fv <- fitted(x) else fv <- sapply(x$models, predict, newdata= list(x = x$sites)) matlines(x$sites, fv, col = col, lty = lty, pch = NA, type = "l", ...) invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fitspecaccum.R
`fitted.capscale` <- function(object, model = c("CCA", "CA", "pCCA", "Imaginary"), type = c("response", "working"), ...) { model <- match.arg(model) if (is.null(object[[model]]) && model != "Imaginary") stop(gettextf("component '%s' does not exist", model)) type <- match.arg(type) ## Return scaled eigenvalues U <- switch(model, CCA = ordiYbar(object, "CCA"), CA = ordiYbar(object, "CA"), Imaginary = object$CA$imaginary.u.eig, pCCA = ordiYbar(object, "pCCA")) if (is.null(U)) stop(gettextf("component '%s' does not exist", model)) ## Distances or working scores U if (type == "response") { U <- dist(U) ## undo sqrt.dist -- sqrt.dist was applied first in capscale, ## so it must be last here if (object$sqrt.dist) U <- U^2 } U }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fitted.capscale.R
`fitted.cca` <- function (object, model = c("CCA","CA","pCCA"), type = c("response", "working"), ...) { type <- match.arg(type) model <- match.arg(model) if (is.null(object[[model]])) stop(gettextf("component '%s' does not exist", model)) Xbar <- ordiYbar(object, model) if (type == "response") { gtot <- object$grand.total rc <- object$rowsum %o% object$colsum Xbar <- (Xbar * sqrt(rc) + rc) * gtot } Xbar }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fitted.cca.R
### 'working' will be Gower's G = -GowerDblcen(dis^2)/2 `fitted.dbrda` <- function (object, model = c("CCA", "CA", "pCCA"), type = c("response", "working"), ...) { ZAP <- sqrt(.Machine$double.eps) type <- match.arg(type) model <- match.arg(model) if (is.null(object[[model]])) stop(gettextf("component '%s' does not exist", model)) D <- ordiYbar(object, model) if (type == "response") { ## revert Gower double centring de <- diag(D) D <- -2 * D + outer(de, de, "+") ## we may have tiny negative zeros: zero them, but let large ## negative values be and give NaN in sqrt (with a warning) D[abs(D) < ZAP] <- 0 if (!object$sqrt.dist) D <- sqrt(D) D <- D * object$adjust D <- as.dist(D) ## we do not remove Lingoes or Cailliez adjustment: this ## typically gives too many negative distances as unadjusted D ## often has zero-values } D }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fitted.dbrda.R
`fitted.procrustes` <- function(object, truemean = TRUE, ...) { fit <- object$Yrot if (truemean) fit <- sweep(fit, 2, object$xmean, "+") fit } ## Like above, except when takes 'newata' `predict.procrustes` <- function(object, newdata, truemean = TRUE, ...) { if (missing(newdata)) return(fitted(object, truemean = truemean)) if (object$symmetric) stop(gettextf("'predict' not available for symmetric procrustes analysis with 'newdata'")) Y <- as.matrix(newdata) ## scaling and rotation Y <- object$scale * Y %*% object$rotation ## translation: always Y <- sweep(Y, 2, object$translation, "+") if (!truemean) Y <- sweep(Y, 2, object$xmean, "-") Y }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fitted.procrustes.R
`fitted.radfit` <- function(object, ...) { out <- sapply(object$models, fitted) if (!length(object$y)) out <- numeric(length(object$models)) if (length(object$y) <= 1) out <- structure(as.vector(out), dim = c(1, length(object$models)), dimnames = list(names(object$y), names(object$models))) out } `fitted.radfit.frame` <- function(object, ...) { lapply(object, fitted, ...) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fitted.radfit.R
`fitted.rda` <- function (object, model = c("CCA", "CA", "pCCA"), type = c("response", "working"), ...) { type <- match.arg(type) model <- match.arg(model) if (is.null(object[[model]])) stop(gettextf("component '%s' does not exist", model)) Xbar <- ordiYbar(object, model) if (type == "response") { cent <- attr(Xbar, "scaled:center") scal <- attr(Xbar, "scaled:scale") if (!is.null(scal)) { Xbar <- sweep(Xbar, 2, scal, "*") attr(Xbar, "scaled:scale") <- NULL } Xbar <- Xbar * sqrt(nrow(Xbar) - 1) Xbar <- sweep(Xbar, 2, cent, "+") attr(Xbar, "scaled:center") <- NULL } Xbar }
/scratch/gouwar.j/cran-all/cranData/vegan/R/fitted.rda.R
### Clarke's dispweight is based on the hypothesis that count data ### should follow Poisson distribution, and species overdispersed to ### the Poisson should be downweighted. The basic model assesses the ### expected values of species and their overdispersion wrt to class ### means for a single factor and then estimates the significance of ### the overdispersion using individual-based simulation within these ### same classes. Function gdispweight generalizes this by allowing a ### formula that specifies any fitted model, but estimates the ### significance of the overdispersion analytically from Pearson ### residuals. `gdispweight` <- function(formula, data, plimit = 0.05) { ## We do not handle missing values (yet?) op <- options(na.action = "na.fail") on.exit(options(op)) ## extract response data comm <- eval(formula[[2]]) ## extract rhs if (missing(data)) data <- environment(formula) x <- model.matrix(delete.response(terms(formula, data = data)), data = data) ## Quasi-Poisson family <- quasipoisson() V <- family$variance ## fit models to all species separately and extract results comm <- as.data.frame(comm) if (any(!sapply(comm, is.numeric))) stop("input data must be numeric") mods <- lapply(comm, function(y) glm.fit(x, y, family = family)) y <- sapply(mods, '[[', "y") mu <- sapply(mods, fitted) wts <- sapply(mods, '[[', "prior.weights") res <- (y-mu) * sqrt(wts) / sqrt(V(mu)) df <- sapply(mods, df.residual) ## the same stats as in Clarke's original, but parametrically stat <- colSums(res^2) p <- pchisq(stat, df, lower.tail = FALSE) dhat <- stat/df w <- ifelse(p < plimit, 1/dhat, 1) ## do not upweight underdispersed species w <- ifelse(w > 1, 1, w) ## done comm <- sweep(comm, 2, w, "*") class(comm) <- c("dispweight", class(comm)) attr(comm, "D") <- dhat attr(comm, "df") <- df attr(comm, "p") <- p attr(comm, "weights") <- w attr(comm, "nsimul") <- NA attr(comm, "nullmodel") <- NA comm }
/scratch/gouwar.j/cran-all/cranData/vegan/R/gdispweight.R
### Interface to the permute package ### input can be (1) a single number giving the number of ### permutations, (2) a how() structure for control parameter in ### permute::shuffleSet, or (3) a permutation matrix which is returned ### as is. In addition, there can be a 'strata' argument which will ### modify case (1). The number of shuffled items must be given in 'N'. `getPermuteMatrix` <- function(perm, N, strata = NULL) { ## 'perm' is either a single number, a how() structure or a ## permutation matrix if (length(perm) == 1) { perm <- how(nperm = perm) } ## apply 'strata', but only if possible: ignore silently other cases if (!missing(strata) && !is.null(strata)) { if (inherits(perm, "how") && is.null(getBlocks(perm))) setBlocks(perm) <- strata } ## now 'perm' is either a how() or a matrix if (inherits(perm, "how")) perm <- shuffleSet(N, control = perm) else { # matrix: check that it *strictly* integer if(!is.integer(perm) && !all(perm == round(perm))) stop("permutation matrix must be strictly integers: use round()") } ## now 'perm' is a matrix (or always was). If it is a plain ## matrix, set minimal attributes for printing. This is a dirty ## kluge: should be handled more cleanly. if (is.null(attr(perm, "control"))) attr(perm, "control") <- structure(list(within=list(type="supplied matrix"), nperm = nrow(perm)), class = "how") perm }
/scratch/gouwar.j/cran-all/cranData/vegan/R/getPermuteMatrix.R
"goodness" <- function(object, ...) UseMethod("goodness")
/scratch/gouwar.j/cran-all/cranData/vegan/R/goodness.R
`goodness.cca` <- function (object, choices, display = c("species", "sites"), model = c("CCA", "CA"), summarize = FALSE, addprevious = FALSE, ...) { display <- match.arg(display) model <- match.arg(model) if (!inherits(object, "cca")) stop("can be used only with objects inheriting from 'cca'") ## See stressplot.capscale for a model to implement goodness() -- ## this can be done, but we don't care to do it for now and we ## just disable this. if (inherits(object, "capscale")) stop("not implemented for 'capscale'") if (inherits(object, c("capscale", "dbrda")) && display == "species") stop(gettextf("cannot analyse species with '%s'", object$method)) v <- sqrt(weights(object, display="species")) * object[[model]]$v if (is.null(v)) stop(gettextf("model = '%s' does not exist", model)) if (display == "sites") u <- sqrt(weights(object, display="sites")) * object[[model]]$u eig <- object[[model]]$eig ## Handle dbrda objects if (!inherits(object, "dbrda")) eig <- eig[eig > 0] if (inherits(object, "dbrda")) { u <- cbind(u, object[[model]][["imaginary.u"]]) display <- "dbrda" } ## get the total variation All <- ordiYbar(object, "initial") if (is.null(All)) stop("old style result object: update() your model") tot <- switch(display, "species" = colSums(All^2), "sites" = rowSums(All^2), "dbrda" = diag(All)) ## take only chosen axes within the component if (!missing(choices)) { choices <- choices[choices <= length(eig)] if (display != "dbrda") v <- v[, choices, drop = FALSE] if (display %in% c("sites", "dbrda")) u <- u[, choices, drop = FALSE] eig <- eig[choices] } if (addprevious) { if (!is.null(object$pCCA)) prev <- ordiYbar(object, "pCCA") else prev <- 0 if (model == "CA" && !is.null(object$CCA)) prev <- prev + ordiYbar(object, "CCA") } if (display == "species") { if (length(eig) == 1) out <- v^2 * eig else out <- t(apply(v^2 %*% diag(eig, nrow=length(eig)), 1, cumsum)) if (addprevious) out <- out + colSums(prev^2) dimnames(out) <- dimnames(v) } else if (display == "sites") { out <- matrix(0, nrow(u), ncol(u)) if (addprevious) mat <- prev else mat <- 0 for (i in seq_len(ncol(u))) { mat <- tcrossprod(u[,i], v[,i]) * sqrt(eig[i]) + mat out[,i] <- rowSums(mat^2) } dimnames(out) <- dimnames(u) } else { # dbrda out <- matrix(0, nrow(u), ncol(u)) mat <- 0 for (i in seq_len(ncol(u))) { mat <- u[,i]^2 * eig[i] + mat out[,i] <- mat } dimnames(out) <- dimnames(u) } if (summarize) out <- out[, ncol(out)] out/tot }
/scratch/gouwar.j/cran-all/cranData/vegan/R/goodness.cca.R
`goodness.metaMDS` <- function(object, dis, ...) { if (inherits(object, "monoMDS")) return(NextMethod("goodness", object, ...)) if (missing(dis)) dis <- metaMDSredist(object) if(attr(dis, "Size") != nrow(object$points)) stop("dimensions do not match in ordination and dissimilarities") d <- order(dis) shep <- Shepard(dis, object$points) res <- (shep$y - shep$yf)^2/sum(shep$y^2) stress <- sqrt(sum(res))*100 if ( abs(stress - object$stress) > 0.001) stop("dissimilarities and ordination do not match") res <- res[order(d)] attr(res, "Size") <- attr(dis, "Size") attr(res, "Labels") <- attr(dis, "Labels") class(res) <- "dist" sqrt(colSums(as.matrix(res))/2*10000) } `goodness.monoMDS` <- function(object, ...) { ## Return vector 'x' for which sum(x^2) == stress stresscomp <- function(y, yf, form) { num <- (y-yf)^2 if (form == 1) den <- sum(y^2) else den <- sum((y-mean(y))^2) num/den } ## Global, local if (object$model %in% c("global", "linear")) { x <- stresscomp(object$dist, object$dhat, object$isform) mat <- matrix(0, object$nobj, object$nobj) for (i in 1:object$ndis) mat[object$iidx[i], object$jidx[i]] <- x[i] res <- sqrt(colSums(mat + t(mat))/2) } ## Local: returns pointwise components of stress else if (object$model == "local") { res <- object$grstress/sqrt(object$ngrp) } else if (object$model == "hybrid" && object$ngrp == 2) { mat <- matrix(0, object$nobj, object$nobj) gr <- seq_len(object$ndis) < object$istart[2] x <- stresscomp(object$dist[gr], object$dhat[gr], object$isform) x <- c(x, stresscomp(object$dist[!gr], object$dhat[!gr], object$isform)) i <- object$iidx j <- object$jidx for (k in 1:object$ndis) { mat[i[k], j[k]] <- mat[i[k], j[k]] + x[k] } res <- sqrt(colSums(mat + t(mat))/4) } else { stop("unknown 'monoMDS' model") } res }
/scratch/gouwar.j/cran-all/cranData/vegan/R/goodness.metaMDS.R
`head.summary.cca` <- function(x, n=6, tail = 0, ...) { print(x, head=n, tail=tail, ...) } `tail.summary.cca` <- function(x, n=6, head = 0, ...) { print(x, head=head, tail=n, ...) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/head.summary.cca.R
`hierParseFormula` <- function (formula, data) { lhs <- formula[[2]] if (any(attr(terms(formula, data = data), "order") > 1)) stop("interactions are not allowed") lhs <- as.matrix(eval(lhs, environment(formula), parent.frame())) formula[[2]] <- NULL rhs <- model.frame(formula, data, drop.unused.levels = TRUE) rhs[] <- lapply(rhs, function(u) { if (!is.factor(u)) u <- factor(u) u }) ## take care that the first column is a unique identifier for rows ## and the last column is constant for pooling all rows together if (length(unique(rhs[,1])) < nrow(rhs)) rhs <- cbind("unit" = factor(seq_len(nrow(rhs))), rhs) if (length(unique(rhs[, ncol(rhs)])) > 1) rhs <- cbind(rhs, "all" = factor(rep(1, nrow(rhs)))) attr(rhs, "terms") <- NULL list(lhs=lhs, rhs=rhs) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/hierParseFormula.R
hiersimu <- function (...) { UseMethod("hiersimu") }
/scratch/gouwar.j/cran-all/cranData/vegan/R/hiersimu.R
hiersimu.default <- function(y, x, FUN, location = c("mean", "median"), relative = FALSE, drop.highest = FALSE, nsimul=99, method = "r2dtable", ...) { ## evaluate formula lhs <- as.matrix(y) if (missing(x)) x <- cbind(level_1=seq_len(nrow(lhs)), leve_2=rep(1, nrow(lhs))) rhs <- data.frame(x) rhs[] <- lapply(rhs, as.factor) rhs[] <- lapply(rhs, droplevels, exclude = NA) nlevs <- ncol(rhs) if (is.null(colnames(rhs))) colnames(rhs) <- paste("level", 1:nlevs, sep="_") tlab <- colnames(rhs) ## check proper design of the model frame l1 <- sapply(rhs, function(z) length(unique(z))) if (!any(sapply(2:nlevs, function(z) l1[z] <= l1[z-1]))) stop("number of levels are inappropriate, check sequence") rval <- list() rval[[1]] <- rhs[,nlevs] nCol <- nlevs - 1 if (nlevs > 1) { nCol <- nlevs - 1 for (i in 2:nlevs) { rval[[i]] <- interaction(rhs[,nCol], rval[[(i-1)]], drop=TRUE) nCol <- nCol - 1 } } rval <- as.data.frame(rval[rev(1:length(rval))]) l2 <- sapply(rval, function(z) length(unique(z))) if (any(l1 != l2)) stop("levels are not perfectly nested") ## aggregate response matrix fullgamma <-if (nlevels(rhs[,nlevs]) == 1) TRUE else FALSE if (fullgamma && drop.highest) nlevs <- nlevs - 1 if (nlevs == 1 && relative) stop("'relative=FALSE' makes no sense with one level") ftmp <- vector("list", nlevs) for (i in 1:nlevs) { ftmp[[i]] <- as.formula(paste("~", tlab[i], "- 1")) } ## is there burnin/thin in ... ? burnin <- if (is.null(list(...)$burnin)) 0 else list(...)$burnin thin <- if (is.null(list(...)$thin)) 1 else list(...)$thin ## evaluate other arguments if (!is.function(FUN)) stop("'FUN' must be a function") location <- match.arg(location) aggrFUN <- switch(location, "mean" = mean, "median" = median) ## this is the function passed to oecosimu evalFUN <- function(x) { if (fullgamma && !drop.highest) { tmp <- lapply(1:(nlevs-1), function(i) t(model.matrix(ftmp[[i]], rhs)) %*% x) tmp[[nlevs]] <- matrix(colSums(x), nrow = 1, ncol = ncol(x)) } else { tmp <- lapply(1:nlevs, function(i) t(model.matrix(ftmp[[i]], rhs)) %*% x) } a <- sapply(1:nlevs, function(i) aggrFUN(FUN(tmp[[i]]))) # dots removed from FUN if (relative) a <- a / a[length(a)] a } ## processing oecosimu results sim <- oecosimu(lhs, evalFUN, method = method, nsimul=nsimul, burnin=burnin, thin=thin) # nam <- paste("level", 1:nlevs, sep=".") # names(sim$statistic) <- attr(sim$oecosimu$statistic, "names") <- nam names(sim$statistic) <- attr(sim$oecosimu$statistic, "names") <- tlab[1:nlevs] call <- match.call() call[[1]] <- as.name("hiersimu") attr(sim, "call") <- call attr(sim, "FUN") <- FUN attr(sim, "location") <- location attr(sim, "n.levels") <- nlevs attr(sim, "terms") <- tlab attr(sim, "model") <- rhs class(sim) <- c("hiersimu", class(sim)) sim }
/scratch/gouwar.j/cran-all/cranData/vegan/R/hiersimu.default.R
`hiersimu.formula` <- function(formula, data, FUN, location = c("mean", "median"), relative = FALSE, drop.highest = FALSE, nsimul=99, method = "r2dtable", ...) { ## evaluate formula if (missing(data)) data <- parent.frame() tmp <- hierParseFormula(formula, data) ## run simulations sim <- hiersimu.default(tmp$lhs, tmp$rhs, FUN = FUN, location = location, relative = relative, drop.highest = drop.highest, nsimul = nsimul, method = method, ...) call <- match.call() call[[1]] <- as.name("hiersimu") attr(sim, "call") <- call sim }
/scratch/gouwar.j/cran-all/cranData/vegan/R/hiersimu.formula.R
### Make a compact summary of permutations. This copies Gav Simpson's ### permute:::print.how, but only displays non-default choices in how(). `howHead` <- function(x, ...) { ## print nothing is this not 'how' if (is.null(x) || !inherits(x, "how")) return() ## collect header head <- NULL ## blocks if (!is.null(getBlocks(x))) head <- paste0(head, paste("Blocks: ", x$blocks.name, "\n")) ## plots plotStr <- getStrata(x, which = "plots") if (!is.null(plotStr)) { plots <- getPlots(x) ptype <- getType(x, which = "plots") head <- paste0(head, paste0("Plots: ", plots$plots.name, ", ")) head <- paste0(head, paste("plot permutation:", ptype)) if(getMirror(x, which = "plots")) head <- paste(head, "mirrored") if (isTRUE(all.equal(ptype, "grid"))) { nr <- getRow(x, which = "plots") nc <- getCol(x, which = "plots") head <- paste0(head, sprintf(ngettext(nr, " %d row", " %d rows"), nr)) head <- paste0(head, sprintf(ngettext(nc, " %d column", " %d columns"), nc)) } head <- paste0(head, "\n") } ## the fine level (within plots if any) type <- getType(x, which = "within") head <- paste0(head, "Permutation: ", type) if (isTRUE(type %in% c("series", "grid"))) { if(getMirror(x, which = "within")) head <- paste(head, "mirrored") if(getConstant(x)) head <- paste0(head, " constant permutation within each Plot") } if (isTRUE(all.equal(type, "grid"))) { nr <- getRow(x, which = "within") nc <- getCol(x, which = "within") head <- paste0(head, sprintf(ngettext(nr, " %d row", " %d rows"), nr)) head <- paste0(head, sprintf(ngettext(nc, " %d column", " %d columns"), nc)) } paste0(head, "\nNumber of permutations: ", getNperm(x), "\n") }
/scratch/gouwar.j/cran-all/cranData/vegan/R/howHead.R
"humpfit" <- function (mass, spno, family = poisson, start) { .Defunct("natto::humpfit() from https://github.com/jarioksa/natto/") hump <- function(p, mass, spno, ...) { x <- ifelse(mass < p[1], mass/p[1], p[1] * p[1]/mass/mass) fv <- p[3] * log(1 + p[2] * x/p[3]) n <- wt <- rep(1, length(x)) dev <- sum(dev.resids(spno, fv, wt)) aicfun(spno, n, fv, wt, dev)/2 } fam <- family(link = "identity") aicfun <- fam$aic dev.resids <- fam$dev.resids if (missing(start)) p <- c(mean(mass), 100, 10) else p <- start fit <- nlm(hump, p = p, mass = mass, spno = spno, hessian = TRUE) p <- fit$estimate names(p) <- c("hump", "scale", "alpha") x <- ifelse(mass < p[1], mass/p[1], p[1] * p[1]/mass/mass) fv <- p[3] * log(1 + p[2] * x/p[3]) res <- dev.resids(spno, fv, rep(1, length(x))) dev <- sum(res) residuals <- spno - fv aic <- fit$minimum * 2 + 6 rdf <- length(x) - 3 out <- list(nlm = fit, family = fam, y = spno, x = mass, coefficients = p, fitted.values = fv, aic = aic, rank = 3, df.residual = rdf, deviance = dev, residuals = residuals, prior.weights = rep(1, length(x))) class(out) <- c("humpfit", "glm") out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/humpfit.R
`identify.ordiplot` <- function (x, what, labels, ...) { x <- scores(x, what) if (missing(labels)) labels <- rownames(x) identify(x, labels = labels, ...) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/identify.ordiplot.R
`indpower` <- function(x, type=0) { x <- as.matrix(x) if (!(is.numeric(x) || is.logical(x))) stop("input data must be numeric") x <- ifelse(x > 0, 1, 0) if (NCOL(x) < 2) stop("provide at least two columns for 'x'") if (!(type %in% 0:2)) stop("'type' must be 0, 1 or 2") n <- nrow(x) j <- crossprod(x) ## faster t(x) %*% x ip1 <- sweep(j, 1, diag(j), "/") ip2 <- 1 - sweep(-sweep(j, 2, diag(j), "-"), 1, n - diag(j), "/") out <- switch(as.character(type), "0" = sqrt(ip1 * ip2), "1" = ip1, "2" = ip2) cn <- if (is.null(colnames(out))) 1:ncol(out) else colnames(out) rn <- if (is.null(rownames(out))) 1:ncol(out) else rownames(out) colnames(out) <- paste("t", cn, sep=".") rownames(out) <- paste("i", rn, sep=".") out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/indpower.R
`inertcomp` <- function (object, display = c("species", "sites"), unity = FALSE, proportional = FALSE) { display <- match.arg(display) ## unity and proportional are conflicting arguments if (unity && proportional) stop("arguments 'unity' and 'proportional' cannot be both TRUE") if (!inherits(object, "cca")) stop("can be used only with objects inheriting from 'cca'") if (inherits(object, c("capscale", "dbrda")) && display == "species") stop(gettextf("cannot analyse species with '%s'", object$method)) if (inherits(object, "dbrda")) { display <- "dbrda" } ## function to get the eigenvalues getComps <- function(x, display) { if(!is.null(x)) switch(display, "species" = colSums(x^2), "sites" = rowSums(x^2), "dbrda" = diag(x) ) } pCCA <- ordiYbar(object, "pCCA") CCA <- ordiYbar(object, "CCA") CA <- ordiYbar(object, "CA") tot <- ordiYbar(object, "initial") out <- cbind("pCCA" = getComps(pCCA, display), "CCA" = getComps(CCA, display), "CA" = getComps(CA, display)) if (unity) ## each column sums to 1 out <- sweep(out, 2, colSums(out), "/") if (proportional) out <- out/getComps(tot, display) out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/inertcomp.R
### influence statistics for cca objects ## extract QR decomposition `qr.cca` <- function(x, ...) { if (is.null(r <- x$CCA$QR)) stop("unconstrained model or rank zero: no 'qr' component") r } ## residual degrees of freedom `df.residual.cca` <- function(object, ...) { nobs(object) - object$CCA$qrank - 1 } ## hat values need adjustment, because QR ignores Intercept `hatvalues.cca` <- function(model, ...) { hat <- rowSums(qr.Q(qr(model))^2) + weights(model) ## it can be be that hat > 1: the trick below is the same as used ## in stats::lm.influence() hat[hat > 1 - 10 * .Machine$double.eps] <- 1 hat } `hatvalues.rda` <- function(model, ...) { hat <- rowSums(qr.Q(qr(model))^2) + 1/nrow(qr(model)$qr) hat[hat > 1 - 10 * .Machine$double.eps] <- 1 hat } ## sigma gives the residual standard deviation. The only unambiguous ## sigma is the residual deviation for species, but for CANOCO like ## statistic this would be residual of WA/LC regression with little or ## no meaning. `sigma.cca` <- function(object, type = c("response", "canoco"), ...) { type <- match.arg(type) ## no response type in distance-based ordination if (inherits(object, c("dbrda", "capscale")) && type == "response") stop("type = 'response' is not available in distance-based ordination") ## response: a vector of species (column) sigmata rdf <- df.residual(object) if (inherits(object, "rda")) adj <- nobs(object) - 1 else adj <- 1 if (type == "response") { sqrt(colSums(ordiYbar(object, "CA")^2 / rdf * adj)) } else { # canoco has WA - LC regression sqrt((colSums(weights(object) * object$CCA$wa^2) - 1)/rdf) } } ## rstandard and rstudent need sigma and have similar restrictions as ## sigma: it should be extractable and meaningful. `rstandard.cca` <- function(model, type = c("response", "canoco"), ...) { type <- match.arg(type) sd <- sigma(model, type = type) hat <- hatvalues(model) if (inherits(model, "rda")) adj <- sqrt(nobs(model) - 1) else adj <- 1 w <- sqrt(weights(model)) res <- switch(type, "response" = ordiYbar(model, "CA") * adj, "canoco" = w * (model$CCA$wa - model$CCA$u)) res <- res / sqrt(1 - hat) res <- sweep(res, 2, sd, "/") res[is.infinite(res)] <- NaN res } ## MASS book (4th ed), Chapter 6.3, p. 152 (e^star) `rstudent.cca` <- function(model, type = c("response", "canoco"), ...) { type <- match.arg(type) np <- df.residual(model) res <- rstandard(model, type = type) res <- res / sqrt(pmax(np-res^2, 0)/(np-1)) res[is.infinite(res)] <- NaN res } ## Cook's distance depends on meaningful sigma `cooks.distance.cca` <- function(model, type = c("response", "canoco"), ...) { hat <- hatvalues(model) p <- model$CCA$qrank d <- rstandard(model, type = type)^2 * hat / (1 - hat) / (p + 1) d[is.infinite(d)] <- NaN d } ## residual sums of squares and products `SSD.cca` <- function(object, type = "canoco", ...) { w <- sqrt(weights(object)) SSD <- crossprod(w * (object$CCA$wa - object$CCA$u)) structure(list(SSD = SSD, call = object$call, df = df.residual(object)), class = "SSD") } ## variances and covariances of coefficients. The sqrt(diag()) will be ## standard errors of regression coefficients, and for constrained ## ordination model m, the t-values of regression coefficients will be ## coef(m)/sqrt(diag(vcov(m))). The kind of relevant coefficient will ## be determined by the output of SSD. `vcov.cca` <- function(object, type = "canoco", ...) { QR <- qr(object) p <- 1L:QR$rank ## we do not give the (Intercept): it is neither in coef() cov.unscaled <- chol2inv(QR$qr[p, p]) dimnames(cov.unscaled) <- list(colnames(QR$qr)[p], colnames(QR$qr)[p]) ssd <- estVar(SSD(object, type = type)) kronecker(ssd, cov.unscaled, make.dimnames = TRUE) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/influence.cca.R
"initMDS" <- function(x, k=2) { nr <- attr(x, "Size") res <- runif(nr*k) dim(res) <- c(nr,k) res }
/scratch/gouwar.j/cran-all/cranData/vegan/R/initMDS.R
`intersetcor` <- function(object) { if (!inherits(object, "cca")) stop("can be used only with objects inheriting from 'cca'") if (is.null(object$CCA) || !object$CCA$rank) stop("no constrained ordination or rank of constraints is zero") wa <- object$CCA$wa X <- qr.X(object$CCA$QR) ## remove conditions (partial terms) if (!is.null(object$pCCA)) { X <- X[, -seq_along(object$pCCA$envcentre), drop = FALSE] X <- qr.resid(object$pCCA$QR, X) } if (inherits(object, "rda")) cor(X, wa) else { # cca: weighted analysis, terms already weighted-centred wa <- sqrt(object$rowsum) * wa cov <- crossprod(X, wa) isd <- outer(1/sqrt(colSums(X^2)), 1/sqrt(colSums(wa^2))) cov * isd } }
/scratch/gouwar.j/cran-all/cranData/vegan/R/intersetcor.R
`isomap` <- function(dist, ndim=10, ...) { dist <- isomapdist(dist, ...) out <- wcmdscale(dist, k=ndim, eig=TRUE) ## some versions of cmdscale may return NaN points corresponding ## to negative eigenvalues. if ((naxes <- sum(out$eig > 0)) < ndim && naxes) { out$points <- out$points[, seq(naxes), drop = FALSE] message(gettextf("isomap returns only %d axes with positive eigenvalues", naxes)) } npoints <- nrow(out$points) net <- matrix(FALSE, nrow=npoints, ncol=npoints) net[lower.tri(net)][attr(dist, "net")] <- TRUE net <- which(net, arr.ind=TRUE) out$method <- attr(dist, "method") out$criterion <- attr(dist, "criterion") out$critval <- attr(dist, "critval") out$take <- attr(dist, "take") out$net <- net out$npoints <- npoints out$call <- match.call() class(out) <- "isomap" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/isomap.R
`isomapdist` <- function(dist, epsilon, k, path="shortest", fragmentedOK = FALSE, ...) { EPS <- 1e-5 op <- options(warn = 2) on.exit(options(op)) if (!inherits(dist, "dist")) dist <- as.dist(dist) options(op) method <- attr(dist, "method") if (missing(epsilon) && missing(k)) stop("either epsilon or k must be given") if (!missing(epsilon) && !missing(k)) message("both epsilon and k given, using epsilon") if (!missing(epsilon)) dist[dist >= epsilon-EPS] <- NA else { dist <- as.matrix(dist) diag(dist) <- NA is.na(dist) <- apply(dist, 2, function(x) x > x[order(x, na.last=TRUE)[k]]) dist <- pmax(as.dist(dist), as.dist(t(dist)), na.rm = TRUE) } fragm <- distconnected(dist, toolong=0, trace=FALSE) take <- NULL if (length(unique(fragm)) > 1) { if (fragmentedOK) { warning("data are fragmented: taking the largest fragment") take <- fragm == as.numeric(names(which.max(table(fragm)))) dist <- as.dist(as.matrix(dist)[take,take]) } else { stop("data are fragmented") } } net <- which(!is.na(dist)) attr(dist, "method") <- method dist <- stepacross(dist, path = path, toolong = 0, trace = FALSE) if (any(is.na(dist))) { ## never get here: we selected non-fragmented subset stop("dissimilarities contain NA and cannot be analysed: file a bug report") } if (missing(epsilon)) { attr(dist, "criterion") <-"k" attr(dist, "critval") <- k } else { attr(dist, "criterion") <- "epsilon" attr(dist, "critval") <- epsilon } attr(dist, "method") <- paste(attr(dist, "method"), "isomap") attr(dist, "net") <- net attr(dist, "take") <- take attr(dist, "call") <- match.call() dist }
/scratch/gouwar.j/cran-all/cranData/vegan/R/isomapdist.R
`kendall.global` <- function(Y, group, nperm=999, mult="holm") { ### Function to test the overall significance of the Kendall coefficient of ### concordance for a single group or several groups of judges (e.g. species) ### ### copyleft - Guillaume Blanchet and Pierre Legendre, October 2008 ################################################################################ mult <- match.arg(mult, c("sidak", p.adjust.methods)) ##CC# Make sure Y is a matrix and find number of rows and columns of Y Y <- as.matrix(Y) n <- nrow(Y) p <- ncol(Y) if(p < 2) stop("there is only one variable in the data matrix") ##CC# Transform the species abundances to ranks, by column R <- apply(Y,2,rank) if(missing(group)) group <- rep(1,p) if(length(group) != p){ stop("the number of species in the vector differs from the total number of species") } group <- as.factor(group) gr.lev <- levels(group) ngr <- nlevels(group) gr <- as.list(1:ngr) n.per.gr <- vector(length=ngr) for(i in 1:ngr){ gr[[i]] <- which(group==gr.lev[i]) n.per.gr[i] <- length(gr[[i]]) ## Vector containing the number of species per group } ## Initialise the vectors of results W.gr <- vector("numeric",ngr) F.gr <- vector("numeric",ngr) prob.F.gr <- vector("numeric",ngr) Chi2.gr <- vector("numeric",ngr) prob.perm.gr <- vector("numeric",ngr) for(i in 1:ngr){ p.i <- n.per.gr[i] if(p.i < 2) stop(gettextf("there is only one variable in group %d",gr.lev[i])) ##CC# Correction factors for tied ranks (eq. 3.3) t.ranks <- apply(R[,gr[[i]]], 2, function(x) summary(as.factor(x), maxsum=n)) T. <- sum(unlist(lapply(t.ranks, function(x) sum((x^3)-x)))) ##CC# Compute the Sum of squares of the uncentred ranks (S) (eq. 3.1) S <- sum(rowSums(R[,gr[[i]]])^2) ##CC# Compute Kendall's W (eq. 3.2) W.gr[i] <- ((12*S)-(3*(p.i^2)*n*(n+1)^2))/(((p.i^2)*((n^3)-n))-(p.i*T.)) ##C# Compute Fisher F statistic and associated probability F.gr[i] <- (p.i-1)*W.gr[i]/(1-W.gr[i]) nu1 <- n-1-(2/p.i) nu2 <- nu1*(p.i-1) prob.F.gr[i] <- pf(F.gr[i], nu1, nu2, lower.tail=FALSE) ##CC# Calculate Friedman's Chi-square (eq. 3.4) Chi2.gr[i] <- p.i*(n-1)*W.gr[i] counter <- 1 for(j in 1:nperm) { # Each species is permuted independently R.perm <- apply(R[,gr[[i]]], 2, sample) S.perm <- sum(rowSums(R.perm)^2) W.perm <- ((12*S.perm)-(3*(p.i^2)*n*(n+1)^2))/(((p.i^2)*((n^3)-n))-(p.i*T.)) Chi2.perm <- p.i*(n-1)*W.perm if(Chi2.perm >= Chi2.gr[i]) counter <- counter+1 } prob.perm.gr[i] <- counter/(nperm+1) } ## Correction to P-values for multiple testing if(ngr > 1) { if(mult == "sidak") { perm.corr <- NA for(i in 1:ngr) perm.corr = c(perm.corr, (1-(1-prob.perm.gr[i])^ngr)) perm.corr <- perm.corr[-1] # prob.F.corr <- NA for(i in 1:ngr) prob.F.corr = c(prob.F.corr, (1-(1-prob.F.gr[i])^ngr)) prob.F.corr <- prob.F.corr[-1] } else { perm.corr <- p.adjust(prob.perm.gr, method=mult) prob.F.corr <- p.adjust(prob.F.gr, method=mult) } } ## Create a data frame containing the results if(ngr == 1) { table <- rbind(W.gr, F.gr, prob.F.gr, Chi2.gr, prob.perm.gr) colnames(table) <- colnames(table,do.NULL = FALSE, prefix = "Group.") rownames(table) <- c("W", "F", "Prob.F", "Chi2", "Prob.perm") } else { table <- rbind(W.gr, F.gr, prob.F.gr, prob.F.corr, Chi2.gr, prob.perm.gr, perm.corr) colnames(table) <- colnames(table,do.NULL = FALSE, prefix = "Group.") rownames(table) <- c("W", "F", "Prob.F", "Corrected prob.F", "Chi2", "Prob.perm", "Corrected prob.perm") } if(ngr == 1) { out <- list(Concordance_analysis=table) } else { out <- list(Concordance_analysis=table, Correction.type=mult) } # class(out) <- "kendall.global" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/kendall.global.R
`kendall.post` <- function(Y, group, nperm=999, mult="holm") { ### Function to carry out a posteriori tests on individual judges (e.g. species) ### for a single group or several groups of judges. ### ### copyleft - Guillaume Blanchet and Pierre Legendre, October 2008 ################################################################################ mult <- match.arg(mult, c("sidak", p.adjust.methods)) ##CC# Make sure Y is a matrix and find number of rows and columns of Y Y <- as.matrix(Y) p <- ncol(Y) if(p < 2) stop("there is only one variable in the data matrix") ##CC# Transform the species abundances to ranks, by column R <- apply(Y,2,rank) if(missing(group)) group <- rep(1,p) if(length(group) != p){ stop("the number of species in the vector differs from the total number of species") } ##CC# Separate tests for the variables in each group group <- as.factor(group) gr.lev <- levels(group) ngr <- nlevels(group) gr <- as.list(1:ngr) n.per.gr <- vector(length=ngr) for(i in 1:ngr){ gr[[i]] <- which(group==gr.lev[i]) n.per.gr[i] <- length(gr[[i]]) # Vector with the number of # variables per group } ##=============================== ##CC# start permutation procedure ##=============================== ##CC# Initialize the counters counter <- as.list(1:ngr) for(i in 1:ngr){ counter[[i]] <- vector(length = n.per.gr[i]) } W.gr <- vector("list",ngr) if(ngr > 1) spear.gr <- vector("list",ngr) for(i in 1:ngr){ p.i <- n.per.gr[i] if(p.i < 2) stop(gettextf("there is only one variable in group %d", gr.lev[i])) #CC# Extract variables part of #group i R.gr <- R[,gr[[i]]] # Table with species of group 'i' only #as columns CC# Calculate the #mean of the Spearman #correlations for each species #in a group spear.mat <- cor(R.gr) diag(spear.mat) <- NA spear.mean <- apply(spear.mat, 1, mean, na.rm=TRUE) #CC# Calculate Kendall's W for each variable W.var <- ((p.i-1)*spear.mean+1)/p.i #for(j in 1:n.per.gr[i]){ for(j in 1:p.i){ # Test each species in turn #CC# Create a new R where the #permuted variable has been #removed R.gr.mod <- R.gr[,-j] ##CC# Set counter counter[[i]][j] <- 1 ##CC# The actual permutation procedure for(k in 1:nperm){ var.perm <- sample(R.gr[,j]) spear.mat.perm <- cor(cbind(R.gr.mod, var.perm)) diag(spear.mat.perm) <- NA spear.mean.j.perm <- mean(spear.mat.perm[p.i,], na.rm=TRUE) W.perm <- ((p.i-1)*spear.mean.j.perm+1)/p.i if(W.perm >= W.var[j]) counter[[i]][j] <- counter[[i]][j]+1 } } W.gr[[i]] <- W.var if(ngr > 1) spear.gr[[i]] <- spear.mean } ##CC# Calculate P-values for(i in 1:ngr) { counter[[i]] <- counter[[i]]/(nperm+1) } ## Correction to P-values for multiple testing ## Write all P-values to a long vector 'vec' vec <- counter[[1]] if(ngr > 1) { for(i in 2:ngr) vec = c(vec, counter[[i]]) } if(length(vec) != p) stop("error in putting together vector 'vec'") if(mult == "sidak") { vec.corr = NA for(i in 1:p) vec.corr = c(vec.corr, (1-(1-vec[i])^p)) vec.corr <- vec.corr[-1] } else { vec.corr <- p.adjust(vec, method=mult) } if(ngr > 1) { vec.gr <- vector("list",ngr) end <- 0 for(i in 1:ngr){ beg <- end+1 end <- end + n.per.gr[i] vec.gr[[i]] <- vec.corr[beg:end] } } ## Create data frames containing the results if(ngr == 1) { table <- rbind(spear.mean, W.var, counter[[1]], vec.corr) rownames(table) <- c("Spearman.mean", "W.per.species", "Prob", "Corrected prob") } else { table <- as.list(1:ngr) for(i in 1:ngr) { table[[i]] <- rbind(spear.gr[[i]], W.gr[[i]], counter[[i]], vec.gr[[i]]) rownames(table[[i]]) <- c("Spearman.mean", "W.per.species", "Prob", "Corrected prob") ## PL: Next line had been lost colnames(table[[i]]) <- colnames(table[[i]], do.NULL = FALSE, prefix = "Spec") } } if(ngr == 1) { out <- list(A_posteriori_tests=table, Correction.type=mult) } else { out <- list(A_posteriori_tests_Group=table, Correction.type=mult) } # class(out) <- "kendall.post" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/kendall.post.R
`labels.envfit` <- function(object, ...) { out <- list("vectors" = rownames(object$vectors$arrows), "factors" = rownames(object$factors$centroids)) if (is.null(out$vectors) || is.null(out$factors)) out <- unlist(out, use.names = FALSE) out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/labels.envfit.R
## S3 lines method for permat `lines.permat` <- function(x, type = "bray", ...) { lines(summary(x)[[match.arg(type, c("bray", "chisq"))]], ...) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/lines.permat.R
"lines.prestonfit" <- function(x, line.col = "red", lwd = 2, ...) { p <- x$coefficients freq <- x$freq oct <- as.numeric(names(freq)) curve(p[3] * exp(-(x-p[1])^2/2/p[2]^2), -1, max(oct), add = TRUE, col = line.col, lwd = lwd, ...) segments(p["mode"], 0, p["mode"], p["S0"], col = line.col, ...) segments(p["mode"] - p["width"], p["S0"] * exp(-0.5), p["mode"] + p["width"], p["S0"] * exp(-0.5), col = line.col, ...) invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/lines.prestonfit.R
`lines.procrustes` <- function(x, type=c("segments", "arrows"), choices=c(1,2), truemean = FALSE, ...) { type <- match.arg(type) X <- x$X[,choices, drop=FALSE] Y <- x$Yrot[, choices, drop=FALSE] if (truemean) { X <- sweep(X, 2, x$xmean[choices], "+") Y <- sweep(Y, 2, x$xmean[choices], "+") } if (type == "segments") ordiArgAbsorber(X[,1], X[,2], Y[,1], Y[,2], FUN = segments, ...) else ordiArgAbsorber(X[,1], X[,2], Y[,1], Y[,2], FUN = arrows, ...) invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/lines.procrustes.R
`lines.radline` <- function (x, ...) { lin <- fitted(x) rnk <- seq(along = lin) lines(rnk, lin, ...) invisible() } `lines.radfit` <- function(x, ...) { matlines(fitted(x), ...) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/lines.radline.R
`lines.spantree` <- function (x, ord, display = "sites", col = 1, ...) { ord <- scores(ord, display = display, ...) tree <- x$kid ## recycle colours and use a mixture of joined points for line segments col <- rep(col, length = nrow(ord)) col <- col2rgb(col)/255 ## average colour for pairs of points col <- rgb(t(col[,-1] + col[,tree])/2) if (x$n > 1) ordiArgAbsorber(ord[-1, 1], ord[-1, 2], ord[tree, 1], ord[tree, 2], col = col, FUN = segments, ...) invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/lines.spantree.R
`linestack` <- function (x, labels, cex = 0.8, side = "right", hoff = 2, air = 1.1, at = 0, add = FALSE, axis = FALSE, ...) { if (length(at) > 1 || length(hoff) > 1 || length(air) > 1 || length(cex) > 1) stop("only one value accepted for arguments 'cex', 'hoff', 'air' and 'at'") x <- drop(x) n <- length(x) misslab <- missing(labels) if (misslab) { labels <- names(x) } if (!is.expression(labels) && !is.character(labels)) { labels <- as.character(labels) # coerce to character only if not expressions } nlab <- length(labels) if (!misslab && n != nlab) { stop(gettextf( "wrong number of supplied 'labels: expected %d, got %d", n, nlab)) } side <- match.arg(side, c("right", "left")) op <- par(xpd = TRUE) on.exit(par(op)) ord <- order(x) x <- x[ord] labels <- labels[ord] pos <- numeric(n) if (!add) { plot(pos, x, type = "n", axes = FALSE, xlab = "", ylab = "", ...) } hoff <- hoff * strwidth("m") ht <- air * strheight(labels, cex = cex) mid <- (n + 1)%/%2 pos[mid] <- x[mid] if (n > 1) { for (i in (mid + 1):n) { pos[i] <- max(x[i], pos[i - 1] + ht[i]) } } if (n > 2) { for (i in (mid - 1):1) { pos[i] <- min(x[i], pos[i + 1] - ht[i]) } } segments(at, x[1], at, x[n]) if (side == "right") { text(at + hoff, pos, labels, pos = 4, cex = cex, offset = 0.2, ...) segments(at, x, at + hoff, pos) } else if (side == "left") { text(at - hoff, pos, labels, pos = 2, cex = cex, offset = 0.2, ...) segments(at, x, at - hoff, pos) } if (axis) axis(if (side == "right") 2 else 4, pos = at, las = 2) invisible(pos[order(ord)]) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/linestack.R
`make.cepnames` <- function (names, seconditem = FALSE) { ## make valid names names <- make.names(names, unique = FALSE, allow_ = FALSE) ## remove trailing and duplicated dots names <- gsub("\\.[\\.]+", ".", names) names <- gsub("\\.$", "", names) ## split by dots and take 4 letters of each element (if several) names <- lapply(strsplit(names, "\\."), function(x) if (length(x) > 1) substring(x, 1, 4) else x ) ## Take first and last element or 8 characters if only one element names <- unlist(lapply(names, function(x) if (length(x) > 1) paste(x[c(1, if(seconditem) 2 else length(x))], collapse = "") else x)) names <- abbreviate(names, 8) ## Final clean-up make.names(names, unique = TRUE) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/make.cepnames.R
## this lists all known algos in vegan and more ## if method is commsim object, it is returned ## if it is character, switch returns the right one, else stop with error ## so it can be used instead of match.arg(method) in other functions ## NOTE: very very long -- but it can be a central repository of algos ## NOTE 2: storage mode coercions are avoided here ## (with no apparent effect on speed), it should be ## handled by nullmodel and commsim characteristics make.commsim <- function(method) { algos <- list( "r00" = commsim(method="r00", binary=TRUE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { out <- matrix(0L, nr * nc, n) for (k in seq_len(n)) out[sample.int(nr * nc, s), k] <- 1L dim(out) <- c(nr, nc, n) out }), "c0" = commsim(method="c0", binary=TRUE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { out <- array(0L, c(nr, nc, n)) J <- seq_len(nc) for (k in seq_len(n)) for (j in J) out[sample.int(nr, cs[j]), j, k] <- 1L out }), "r0" = commsim(method="r0", binary=TRUE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { out <- array(0L, c(nr, nc, n)) I <- seq_len(nr) for (k in seq_len(n)) for (i in I) out[i, sample.int(nc, rs[i]), k] <- 1L out }), "r1" = commsim(method="r1", binary=TRUE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { out <- array(0L, c(nr, nc, n)) I <- seq_len(nr) storage.mode(cs) <- "double" for (k in seq_len(n)) for (i in I) out[i, sample.int(nc, rs[i], prob=cs), k] <- 1L out }), "r2" = commsim(method="r2", binary=TRUE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { out <- array(0L, c(nr, nc, n)) p <- cs * cs I <- seq_len(nr) for (k in seq_len(n)) for (i in I) out[i, sample.int(nc, rs[i], prob=p), k] <- 1L out }), "quasiswap" = commsim(method="quasiswap", binary=TRUE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") out <- array(unlist(r2dtable(n, rs, cs)), c(nr, nc, n)) storage.mode(out) <- "integer" .Call(do_qswap, out, n, thin, "quasiswap") }), "greedyqswap" = commsim(method="greedyqswap", binary=TRUE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") out <- array(unlist(r2dtable(n, rs, cs)), c(nr, nc, n)) storage.mode(out) <- "integer" .Call(do_greedyqswap, out, n, thin, fill) }), "swap" = commsim(method="swap", binary = TRUE, isSeq=TRUE, mode = "integer", fun = function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { .Call(do_swap, as.matrix(x), n, thin, "swap") }), "tswap" = commsim(method="tswap", binary = TRUE, isSeq=TRUE, mode = "integer", fun = function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { .Call(do_swap, as.matrix(x), n, thin, "trialswap") }), "curveball" = commsim(method="curveball", binary = TRUE, isSeq=TRUE, mode = "integer", fun = function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { .Call(do_curveball, as.matrix(x), n, thin) }), "backtrack" = commsim(method="backtrack", binary = TRUE, isSeq = FALSE, mode = "integer", fun = function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { .Call(do_backtrack, n, rs, cs) }), "r2dtable" = commsim(method="r2dtable", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, cs, rs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") out <- array(unlist(r2dtable(n, rs, cs)), c(nr, nc, n)) storage.mode(out) <- "integer" out }), "swap_count" = commsim(method="swap_count", binary = FALSE, isSeq=TRUE, mode = "integer", fun = function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { .Call(do_swap, as.matrix(x), n, thin, "swapcount") }), "quasiswap_count" = commsim(method="quasiswap_count", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") out <- array(unlist(r2dtable(n, rs, cs)), c(nr, nc, n)) storage.mode(out) <- "integer" .Call(do_qswap, out, n, fill, "rswapcount") }), "swsh_samp" = commsim(method="swsh_samp", binary=FALSE, isSeq=FALSE, mode="double", fun=function(x, n, nr, nc, cs, rs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") nz <- x[x > 0] out <- array(unlist(r2dtable(n, rf, cf)), c(nr, nc, n)) ## do_qswap changes 'out' within the function .Call(do_qswap, out, n, thin, "quasiswap") storage.mode(out) <- "double" for (k in seq_len(n)) { out[,,k][out[,,k] > 0] <- sample(nz) # we assume that length(nz)>1 } out }), "swsh_both" = commsim(method="swsh_both", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, cs, rs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") indshuffle <- function(x) { drop(rmultinom(1, sum(x), rep(1, length(x)))) } nz <- as.integer(x[x > 0]) out <- array(unlist(r2dtable(n, rf, cf)), c(nr, nc, n)) .Call(do_qswap, out, n, thin, "quasiswap") storage.mode(out) <- "integer" for (k in seq_len(n)) { out[,,k][out[,,k] > 0] <- indshuffle(nz - 1L) + 1L # we assume that length(nz)>1 } out }), "swsh_samp_r" = commsim(method="swsh_samp_r", binary=FALSE, isSeq=FALSE, mode="double", fun=function(x, n, nr, nc, cs, rs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") out <- array(unlist(r2dtable(n, rf, cf)), c(nr, nc, n)) .Call(do_qswap, out, n, thin, "quasiswap") storage.mode(out) <- "double" I <- seq_len(nr) for (k in seq_len(n)) { for (i in I) { nz <- x[i,][x[i,] > 0] if (length(nz) == 1) out[i,,k][out[i,,k] > 0] <- nz if (length(nz) > 1) out[i,,k][out[i,,k] > 0] <- sample(nz) } } out }), "swsh_samp_c" = commsim(method="swsh_samp_c", binary=FALSE, isSeq=FALSE, mode="double", fun=function(x, n, nr, nc, cs, rs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") out <- array(unlist(r2dtable(n, rf, cf)), c(nr, nc, n)) .Call(do_qswap, out, n, thin, "quasiswap") storage.mode(out) <- "double" J <- seq_len(nc) for (k in seq_len(n)) { for (j in J) { nz <- x[,j][x[,j] > 0] if (length(nz) == 1) out[,j,k][out[,j,k] > 0] <- nz if (length(nz) > 1) out[,j,k][out[,j,k] > 0] <- sample(nz) } } out }), "swsh_both_r" = commsim(method="swsh_both_r", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, cs, rs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") indshuffle <- function(x) { drop(rmultinom(1, sum(x), rep(1, length(x)))) } I <- seq_len(nr) out <- array(unlist(r2dtable(n, rf, cf)), c(nr, nc, n)) .Call(do_qswap, out, n, thin, "quasiswap") storage.mode(out) <- "integer" for (k in seq_len(n)) { for (i in I) { nz <- as.integer(x[i,][x[i,] > 0]) if (length(nz) == 1) out[i,,k][out[i,,k] > 0] <- nz if (length(nz) > 1) out[i,,k][out[i,,k] > 0] <- indshuffle(nz - 1L) + 1L } } out }), "swsh_both_c" = commsim(method="swsh_both_c", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, cs, rs, rf, cf, s, fill, thin) { if (nr < 2L || nc < 2L) stop("needs at least two items") indshuffle <- function(x) { drop(rmultinom(1, sum(x), rep(1, length(x)))) } J <- seq_len(nc) out <- array(unlist(r2dtable(n, rf, cf)), c(nr, nc, n)) .Call(do_qswap, out, n, thin, "quasiswap") storage.mode(out) <- "integer" for (k in seq_len(n)) { for (j in J) { nz <- as.integer(x[,j][x[,j] > 0]) if (length(nz) == 1) out[,j,k][out[,j,k] > 0] <- nz if (length(nz) > 1) out[,j,k][out[,j,k] > 0] <- indshuffle(nz - 1L) + 1L } } out }), "abuswap_r" = commsim(method="abuswap_r", binary=FALSE, isSeq=TRUE, mode="double", fun=function(x, n, nr, nc, cs, rs, rf, cf, s, fill, thin) { .Call(do_abuswap, as.matrix(x), n, thin, 1L) }), "abuswap_c" = commsim(method="abuswap_c", binary=FALSE, isSeq=TRUE, mode="double", fun=function(x, n, nr, nc, cs, rs, rf, cf, s, fill, thin) { .Call(do_abuswap, as.matrix(x), n, thin, 0L) }), "r00_samp" = commsim(method="r00_samp", binary=FALSE, isSeq=FALSE, mode="double", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { out <- matrix(0, nr * nc, n) for (k in seq_len(n)) out[, k] <- sample(x) dim(out) <- c(nr, nc, n) out }), "c0_samp" = commsim(method="c0_samp", binary=FALSE, isSeq=FALSE, mode="double", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { out <- array(0, c(nr, nc, n)) J <- seq_len(nc) for (k in seq_len(n)) for (j in J) out[, j, k] <- if (nr < 2) x[,j] else sample(x[,j]) out }), "r0_samp" = commsim(method="r0_samp", binary=FALSE, isSeq=FALSE, mode="double", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { out <- array(0, c(nr, nc, n)) I <- seq_len(nr) for (k in seq_len(n)) for (i in I) out[i, , k] <- if (nc < 2) x[i,] else sample(x[i,]) out }), "r00_ind" = commsim(method="r00_ind", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { indshuffle <- function(x) { drop(rmultinom(1, sum(x), rep(1, length(x)))) } out <- matrix(0L, nr * nc, n) for (k in seq_len(n)) out[, k] <- indshuffle(x) dim(out) <- c(nr, nc, n) out }), "c0_ind" = commsim(method="c0_ind", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { indshuffle <- function(x) { drop(rmultinom(1, sum(x), rep(1, length(x)))) } out <- array(0L, c(nr, nc, n)) J <- seq_len(nc) for (k in seq_len(n)) for (j in J) out[, j, k] <- indshuffle(x[,j]) out }), "r0_ind" = commsim(method="r0_ind", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { indshuffle <- function(x) { drop(rmultinom(1, sum(x), rep(1, length(x)))) } out <- array(0L, c(nr, nc, n)) I <- seq_len(nr) for (k in seq_len(n)) for (i in I) out[i, , k] <- indshuffle(x[i,]) out }), "r00_both" = commsim(method="r00_both", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { indshuffle <- function(x) { drop(rmultinom(1, sum(x), rep(1, length(x)))) } out <- matrix(0L, nr * nc, n) for (k in seq_len(n)) { out[,k][x > 0] <- indshuffle(x[x > 0] - 1L) + 1L out[,k] <- sample(out[,k]) } dim(out) <- c(nr, nc, n) out }), "c0_both" = commsim(method="c0_both", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { indshuffle <- function(x) { drop(rmultinom(1, sum(x), rep(1, length(x)))) } out <- array(0L, c(nr, nc, n)) J <- seq_len(nc) for (k in seq_len(n)) for (j in J) { if (sum(x[,j]) > 0) { out[,j,k][x[,j] > 0] <- indshuffle(x[,j][x[,j] > 0] - 1L) + 1L out[,j,k] <- if (nr < 2) out[,j,k] else sample(out[,j,k]) } } out }), "r0_both" = commsim(method="r0_both", binary=FALSE, isSeq=FALSE, mode="integer", fun=function(x, n, nr, nc, rs, cs, rf, cf, s, fill, thin) { indshuffle <- function(x) { drop(rmultinom(1, sum(x), rep(1, length(x)))) } out <- array(0L, c(nr, nc, n)) I <- seq_len(nr) for (k in seq_len(n)) for (i in I) { if (sum(x[i,]) > 0) { out[i,,k][x[i,] > 0] <- indshuffle(x[i,][x[i,] > 0] - 1L) + 1L out[i,,k] <- if (nc < 2) out[i,,k] else sample(out[i,,k]) } } out }) ) if (missing(method)) return(names(algos)) if (inherits(method, "commsim")) return(method) method <- match.arg(method, sort(names(algos))) algos[[method]] }
/scratch/gouwar.j/cran-all/cranData/vegan/R/make.commsim.R
`mantel` <- function (xdis, ydis, method = "pearson", permutations = 999, strata = NULL, na.rm = FALSE, parallel = getOption("mc.cores")) { EPS <- sqrt(.Machine$double.eps) xdis <- as.dist(xdis) ydis <- as.vector(as.dist(ydis)) ## Handle missing values if (na.rm) use <- "complete.obs" else use <- "all.obs" statistic <- cor(as.vector(xdis), ydis, method = method, use = use) variant <- match.arg(method, eval(formals(cor)$method)) variant <- switch(variant, pearson = "Pearson's product-moment correlation", kendall = "Kendall's rank correlation tau", spearman = "Spearman's rank correlation rho", variant) N <- attr(xdis, "Size") permat <- getPermuteMatrix(permutations, N, strata = strata) if (ncol(permat) != N) stop(gettextf("'permutations' have %d columns, but data have %d observations", ncol(permat), N)) permutations <- nrow(permat) if (permutations) { perm <- numeric(permutations) ## asdist as an index selects lower diagonal like as.dist, ## but is faster since it does not set 'dist' attributes xmat <- as.matrix(xdis) asdist <- row(xmat) > col(xmat) ptest <- function(take, ...) { permvec <- (xmat[take, take])[asdist] drop(cor(permvec, ydis, method = method, use = use)) } ## Parallel processing if (is.null(parallel)) parallel <- 1 hasClus <- inherits(parallel, "cluster") if (hasClus || parallel > 1) { if(.Platform$OS.type == "unix" && !hasClus) { perm <- do.call(rbind, mclapply(1:permutations, function(i, ...) ptest(permat[i,],...), mc.cores = parallel)) } else { if (!hasClus) { parallel <- makeCluster(parallel) } perm <- parRapply(parallel, permat, ptest) if (!hasClus) stopCluster(parallel) } } else { perm <- sapply(1:permutations, function(i, ...) ptest(permat[i,], ...)) } signif <- (sum(perm >= statistic - EPS) + 1)/(permutations + 1) } else { signif <- NA perm <- NULL } res <- list(call = match.call(), method = variant, statistic = statistic, signif = signif, perm = perm, permutations = permutations, control = attr(permat, "control")) class(res) <- "mantel" res }
/scratch/gouwar.j/cran-all/cranData/vegan/R/mantel.R
`mantel.correlog` <- function(D.eco, D.geo=NULL, XY=NULL, n.class=0, break.pts=NULL, cutoff=TRUE, r.type="pearson", nperm=999, mult="holm", progressive=TRUE) { r.type <- match.arg(r.type, c("pearson", "spearman", "kendall")) mult <- match.arg(mult, c("sidak", p.adjust.methods)) epsilon <- .Machine$double.eps D.eco <- as.matrix(D.eco) ## Geographic distance matrix if(!is.null(D.geo)) { if(!is.null(XY)) stop("you provided both a geographic distance matrix and a list of site coordinates:\nwhich one should the function use?") D.geo <- as.matrix(D.geo) } else { if(is.null(XY)) { stop("you did not provide a geographic distance matrix nor a list of site coordinates") } else { D.geo <- as.matrix(dist(XY)) } } n <- nrow(D.geo) if(n != nrow(D.eco)) stop("numbers of objects in D.eco and D.geo are not equal") n.dist <- n*(n-1)/2 vec.D <- as.vector(as.dist(D.geo)) vec.DD <- as.vector(D.geo) ## Number of classes and breakpoints if(!is.null(break.pts)) { ## Use the list of break points if(n.class > 0) stop("you provided both a number of classes and a list of break points:\nwhich one should the function use?") n.class = length(break.pts) - 1 } else { ## No breakpoints have been provided: equal-width classes if(n.class == 0) { ## Use Sturges rule to determine the number of classes n.class <- ceiling(1 + log(n.dist, base=2)) } ## Compute the breakpoints from n.class start.pt <- min(vec.D) end.pt <- max(vec.D) width <- (end.pt - start.pt)/n.class break.pts <- vector(length=n.class+1) break.pts[n.class+1] <- end.pt for(i in 1:n.class) break.pts[i] <- start.pt + width*(i-1) } half.cl <- n.class %/% 2 ## Move the first breakpoint a little bit to the left break.pts[1] <- break.pts[1] - epsilon ## Find the break points and the class indices class.ind <- break.pts[1:n.class] + (0.5*(break.pts[2:(n.class+1)]-break.pts[1:n.class])) ## Create the matrix of distance classes vec2 <- vector(length=n^2) for(i in 1:n^2) vec2[i] <- min( which(break.pts >= vec.DD[i]) ) - 1 ## Start assembling the vectors of results class.index <- NA n.dist <- NA mantel.r <- NA mantel.p <- NA ## check.sums = matrix(NA,n.class,1) ## Create a model-matrix for each distance class, then compute a Mantel test for(k in 1:n.class) { class.index <- c(class.index, class.ind[k]) vec3 <- rep(0, n*n) sel <- which(vec2 == k) vec3[sel] <- 1 mat.D2 <- matrix(vec3,n,n) diag(mat.D2) <- 0 n.dis <- sum(mat.D2) n.dist <- c(n.dist, n.dis) if(n.dis == 0) { mantel.r <- c(mantel.r, NA) mantel.p <- c(mantel.p, NA) } else { row.sums <- rowSums(mat.D2) ## check.sums[k,1] = length(which(row.sums == 0)) if((cutoff==FALSE) || !(cutoff==TRUE && k > half.cl && any(row.sums == 0))) { temp <- mantel(mat.D2, D.eco, method=r.type, permutations=nperm) mantel.r <- c(mantel.r, -temp$statistic) temp.p <- temp$signif ## The mantel() function produces a one-tailed p-value ## (H1: r>0) Here, compute a one-tailed p-value in ## direction of the sign if(temp$statistic < 0) { temp.p <- (sum(temp$perm <= temp$statistic)+1)/(nperm+1) } mantel.p <- c(mantel.p, temp.p) } else { mantel.r <- c(mantel.r, NA) mantel.p <- c(mantel.p, NA) } } } mantel.res <- cbind(class.index, n.dist, mantel.r, mantel.p) mantel.res <- mantel.res[-1,] ## Note: vector 'mantel.p' starts with a NA value mantel.p <- mantel.p[-1] n.tests <- length(which(!is.na(mantel.p))) if(mult == "none") { colnames(mantel.res) <- c("class.index", "n.dist", "Mantel.cor", "Pr(Mantel)") } else { ## Correct P-values for multiple testing if(progressive) { p.corr <- mantel.p[1] if(mult == "sidak") { for(j in 2:n.tests) p.corr <- c(p.corr, 1-(1-mantel.p[j])^j) } else { for(j in 2:n.tests) { temp <- p.adjust(mantel.p[1:j], method=mult) p.corr <- c(p.corr, temp[j]) } } } else { ## Correct all p-values for 'n.tests' simultaneous tests if(mult == "sidak") { p.corr <- 1 - (1 - mantel.p[1:n.tests])^n.tests } else { p.corr <- p.adjust(mantel.p[1:n.tests], method=mult) } } temp <- c(p.corr, rep(NA,(n.class-n.tests))) mantel.res <- cbind(mantel.res, temp) colnames(mantel.res) <- c("class.index", "n.dist", "Mantel.cor", "Pr(Mantel)", "Pr(corrected)") } rownames(mantel.res) <- rownames(mantel.res,do.NULL = FALSE, prefix = "D.cl.") ## Output the results res <- list(mantel.res=mantel.res, n.class=n.class, break.pts=break.pts, mult=mult, n.tests=n.tests, call=match.call() ) class(res) <- "mantel.correlog" res }
/scratch/gouwar.j/cran-all/cranData/vegan/R/mantel.correlog.R
`mantel.partial` <- function (xdis, ydis, zdis, method = "pearson", permutations = 999, strata = NULL, na.rm = FALSE, parallel = getOption("mc.cores")) { EPS <- sqrt(.Machine$double.eps) part.cor <- function(rxy, rxz, ryz) { (rxy - rxz * ryz)/sqrt(1-rxz*rxz)/sqrt(1-ryz*ryz) } xdis <- as.dist(xdis) ydis <- as.vector(as.dist(ydis)) zdis <- as.vector(as.dist(zdis)) ## Handle missing values if (na.rm) use <- "complete.obs" else use <- "all.obs" rxy <- cor(as.vector(xdis), ydis, method = method, use = use) rxz <- cor(as.vector(xdis), zdis, method = method, use = use) ryz <- cor(ydis, zdis, method = method, use = use) variant <- match.arg(method, eval(formals(cor)$method)) variant <- switch(variant, pearson = "Pearson's product-moment correlation", kendall = "Kendall's rank correlation tau", spearman = "Spearman's rank correlation rho", variant) statistic <- part.cor(rxy, rxz, ryz) N <- attr(xdis, "Size") permat <- getPermuteMatrix(permutations, N, strata = strata) if (ncol(permat) != N) stop(gettextf("'permutations' have %d columns, but data have %d observations", ncol(permat), N)) permutations <- nrow(permat) if (permutations) { N <- attr(xdis, "Size") perm <- rep(0, permutations) xmat <- as.matrix(xdis) asdist <- row(xmat) > col(xmat) ptest <- function(take, ...) { permvec <- (xmat[take, take])[asdist] rxy <- cor(permvec, ydis, method = method, use = use) rxz <- cor(permvec, zdis, method = method, use = use) part.cor(rxy, rxz, ryz) } ## parallel processing if (is.null(parallel)) parallel <- 1 hasClus <- inherits(parallel, "cluster") if (hasClus || parallel > 1) { if(.Platform$OS.type == "unix" && !hasClus) { perm <- do.call(rbind, mclapply(1:permutations, function(i, ...) ptest(permat[i,],...), mc.cores = parallel)) } else { if (!hasClus) { parallel <- makeCluster(parallel) } perm <- parRapply(parallel, permat, ptest) if (!hasClus) stopCluster(parallel) } } else { perm <- sapply(1:permutations, function(i, ...) ptest(permat[i,], ...)) } signif <- (sum(perm >= statistic - EPS)+1)/(permutations + 1) } else { signif <- NA perm <- NULL } res <- list(call = match.call(), method = variant, statistic = statistic, signif = signif, perm = perm, permutations = permutations, control = attr(permat, "control")) if (!missing(strata)) { res$strata <- deparse(substitute(strata)) res$stratum.values <- strata } class(res) <- c("mantel.partial", "mantel") res }
/scratch/gouwar.j/cran-all/cranData/vegan/R/mantel.partial.R
`meandist` <- function(dist, grouping, ...) { if (!inherits(dist, "dist")) stop("'dist' must be dissimilarity object inheriting from", dQuote(dist)) ## check that 'dist' are dissimilarities (non-negative) if (any(dist < -sqrt(.Machine$double.eps))) warning("some dissimilarities are negative: is this intentional?") grouping <- factor(grouping, exclude = NULL) ## grouping for rows and columns grow <- grouping[as.dist(row(as.matrix(dist)))] gcol <- grouping[as.dist(col(as.matrix(dist)))] ## The row index must be "smaller" of the factor levels so that ## all means are in the lower triangle, and upper is NA first <- as.numeric(grow) >= as.numeric(gcol) cl1 <- ifelse(first, grow, gcol) cl2 <- ifelse(!first, grow, gcol) ## Cannot have within-group dissimilarity for group size 1 n <- table(grouping) take <- matrix(TRUE, nlevels(grouping), nlevels(grouping)) diag(take) <- n > 1 take[upper.tri(take)] <- FALSE out <- matrix(NA, nlevels(grouping), nlevels(grouping)) ## Get output matrix tmp <- tapply(dist, list(cl1, cl2), mean) out[take] <- tmp[!is.na(tmp)] out[upper.tri(out)] <- t(out)[upper.tri(out)] rownames(out) <- colnames(out) <- levels(grouping) class(out) <- c("meandist", "matrix") attr(out, "n") <- table(grouping) out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/meandist.R
`metaMDS` <- function (comm, distance = "bray", k = 2, try = 20, trymax = 20, engine = c("monoMDS", "isoMDS"), autotransform = TRUE, noshare = (engine == "isoMDS"), wascores = TRUE, expand = TRUE, trace = 1, plot = FALSE, previous.best, ...) { engine <- match.arg(engine) ## take care that try (minimum) is not larger than trymax (maximum) if (try > trymax) try <- trymax ## This could be a character vector of length > 1L commname <- deparse(substitute(comm), width.cutoff = 500L) if (length(commname) > 1L) { paste(commname, collapse = "", sep = "") ## deparse can add more white space, so cull 2 or more spaces to a single space commname <- gsub("[ ]{2,}", " ", commname) } ## metaMDS was written for community data which should be all ## positive. Check this here, and set arguments so that they are ## suitable for non-negative data. if (any(autotransform, noshare > 0, wascores) && any(comm < 0, na.rm=TRUE)) { message("'comm' has negative data: 'autotransform', 'noshare' and 'wascores' set to FALSE") wascores <- FALSE autotransform <- FALSE noshare <- FALSE } if (inherits(comm, "dist")) { dis <- comm if (is.null(attr(dis, "method"))) attr(dis, "method") <- "user supplied" wascores <- FALSE } else if ((is.matrix(comm) || is.data.frame(comm)) && isSymmetric(unname(as.matrix(comm)))) { dis <- as.dist(comm) attr(dis, "method") <- "user supplied" wascores <- FALSE } else { if (trace > 2) cat(">>> Calculation of dissimilarities\n") dis <- metaMDSdist(comm, distance = distance, autotransform = autotransform, noshare = noshare, trace = trace, commname = commname, ...) } if (missing(previous.best)) previous.best <- NULL if (trace > 2) cat(">>> NMDS iterations\n") out <- metaMDSiter(dis, k = k, try = try, trymax = trymax, trace = trace, plot = plot, previous.best = previous.best, engine = engine, ...) ## Nearly zero stress is usually not a good thing but a symptom of ## a problem: you may have insufficient data for NMDS if (out$stress < 1e-3) { warning("stress is (nearly) zero: you may have insufficient data") } if (trace > 2) cat(">>> Post-processing NMDS\n") points <- postMDS(out$points, dis, plot = max(0, plot - 1), ...) ## rescale monoMDS scaling if postMDS scaled 'points' if (engine == "monoMDS" && !is.null(scl <- attr(points, "internalscaling"))) { out$dist <- out$dist/scl out$dhat <- out$dhat/scl } if (is.null(rownames(points))) rownames(points) <- rownames(comm) wa <- if (wascores) { ## transformed data ##comm <- eval.parent(parse(text=attr(dis, "commname"))) comm <- attr(dis, "comm") wascores(points, comm, expand = expand) } else { NA } out$points <- points out$species <- wa out$call <- match.call() if (is.null(out$data)) out$data <- commname class(out) <- c("metaMDS", class(out)) out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/metaMDS.R
`metaMDSdist` <- function (comm, distance = "bray", autotransform = TRUE, noshare = TRUE, trace = 1, commname, zerodist = "ignore", distfun = vegdist, ...) { ## metaMDSdist should get a raw data matrix, but if it gets a ## 'dist' object return that unchanged and quit silently. if (inherits(comm, "dist") || ((is.matrix(comm) || is.data.frame(comm)) && isSymmetric(unname(as.matrix(comm))))) return(comm) distname <- deparse(substitute(distfun)) distfun <- match.fun(distfun) zerodist <- match.arg(zerodist, c("fail", "add", "ignore")) formals(distfun) <- c(formals(distfun), alist(... = )) formals(stepacross) <- c(formals(stepacross), alist(... = )) if (missing(commname)) commname <- deparse(substitute(comm)) xam <- max(comm) if (autotransform && xam > 50) { comm <- sqrt(comm) commname <- paste("sqrt(", commname, ")", sep = "") if (trace) cat("Square root transformation\n") } if (autotransform && xam > 9) { comm <- wisconsin(comm) commname <- paste("wisconsin(", commname, ")", sep = "") if (trace) cat("Wisconsin double standardization\n") } dis <- distfun(comm, method = distance, ...) call <- attr(dis, "call") call[[1]] <- as.name(distname) attr(dis, "call") <- call if (zerodist != "ignore" && any(dis <= 0, na.rm = TRUE)) { if (zerodist == "fail") stop("zero-value dissimilarities are not allowed") else if (zerodist == "add") { zero <- min(dis[dis > 0], na.rm = TRUE)/2 dis[dis <= 0] <- zero if (trace) cat("Zero dissimilarities changed into ", zero,"\n") } } ## We actually used maxdiss to decide whether index has a closed ## upper limit, but data maximum does not give that ## info. vegan::vegdist returns the info as an attribute of dis, ## but for other distance functions we guess constant maximum with ## arbitrary data matrix. This test is known to fail in some ## cases, but better so than assuming wrong maxdist: for instance, ## stats::dist(x, method="canberra") has maxdist ncol(x) -- ## vegan::vegdist(x, "canberra") has maxdist 1, and we voluntarily ## fail here with stats::dist. if (is.null(attr(dis, "maxdist"))) { mat <- matrix(c(1,0,0, 1,0,0, 0,7,0, 0,3,0, 0,0,0.2,0,0,10), nrow=3) dmat <- distfun(mat, method = distance, ...) if (sd(dmat) < sqrt(.Machine$double.eps) && max(dis) - max(dmat) < sqrt(.Machine$double.eps)) { maxdis <- max(dmat) attr(dis, "maxdist") <- maxdis message("assuming that theoretical maximum distance is ", maxdis) } else { attr(dis, "maxdist") <- NA } } ## sanity check of dissimilarities: either similarities or failed ## logic above maxdis <- attr(dis, "maxdist") if (!is.null(maxdis) && is.numeric(maxdis)) { if (max(dis) > maxdis + sqrt(.Machine$double.eps)) { warning("some dissimilarities exceed expected maximum ", maxdis) attr(dis, "maxdist") <- NA } if(maxdis < sqrt(.Machine$double.eps)) warning("perhaps you have similarities instead of dissimilarities?") } if ((isTRUE(noshare) && any(tmp <- no.shared(comm))) || (!is.logical(noshare) && noshare >= 0 && sum(tmp <- no.shared(comm))/length(dis) > noshare)) { if (trace) cat("Using step-across dissimilarities:\n") rn <- range(dis[tmp], na.rm = TRUE) if (rn[2]/rn[1] > 1.01) warning("non-constant distances between points with nothing shared\n", " stepacross may be meaningless: consider argument 'noshare=0'") is.na(dis) <- tmp dis <- stepacross(dis, trace = trace, toolong=0, ...) if (length(unique(distconnected(tmp, trace = trace))) > 1) warning("data are disconnected, results may be meaningless") } attr(dis, "commname") <- commname attr(dis, "comm") <- comm attr(dis, "function") <- distname dis }
/scratch/gouwar.j/cran-all/cranData/vegan/R/metaMDSdist.R
`metaMDSiter` <- function (dist, k = 2, try = 20, trymax = 20, trace = 1, plot = FALSE, previous.best, engine = "monoMDS", maxit = 200, parallel = getOption("mc.cores"), ...) { engine <- match.arg(engine, c("monoMDS", "isoMDS")) EPS <- 0.05 if (engine == "monoMDS") EPS <- EPS/100 # monoMDS stress (0,1), isoMDS (0,100) RESLIM <- 0.01 RMSELIM <- 0.005 converged <- 0 ## set tracing for engines isotrace <- max(0, trace - 1) monotrace <- engine == "monoMDS" && trace > 1 ## explain monoMDS convergence codes (sol$icause) monomsg <- c("no. of iterations >= maxit", "stress < smin", "stress ratio > sratmax", "scale factor of the gradient < sfgrmin") ## monoMDS trace >= 2 monostop <- function(mod) { if (mod$maxits == 0) return(NULL) lab <- monomsg[mod$icause] cat(" ", mod$iters, "iterations: ", lab, "\n") } ## collect monoMDS convergence code for trace if (trace && engine == "monoMDS") stopcoz <- numeric(4) ## Previous best or initial configuration if (!missing(previous.best) && !is.null(previous.best)) { ## check if previous.best is from metaMDS or isoMDS if (inherits(previous.best, "metaMDS") || is.list(previous.best) && all(c("points", "stress") %in% names(previous.best))) { ## Previous best may come from another 'engine' or ## 'model': extract its 'points' and use as an initial ## configuration with 'maxit = 0' to evaluate the stress ## in current case, or take a matrix as configuration. init <- previous.best$points bestry <- previous.best$bestry trybase <- previous.best$tries converged <- previous.best$converged nc <- NCOL(init) if (nc > k) init <- init[, 1:k, drop = FALSE] else if (nc < k) for (i in 1:(k-nc)) init <- cbind(init, runif(NROW(init), -0.1, 0.1)) if (trace) cat(sprintf("Starting from %d-dimensional configuration\n", nc)) } else { init <- as.matrix(previous.best) bestry <- 0 trybase <- 0 } ## evaluate stress s0 <- switch(engine, "monoMDS" = monoMDS(dist, y = init, k = k, maxit = 0, ...), "isoMDS" = isoMDS(dist, y = init, k = k, maxit = 0)) ## Check whether model changed if (is.list(previous.best) && !is.null(previous.best$stress) && !isTRUE(all.equal(previous.best$stress, s0$stress))) { if (trace) cat("Stress differs from 'previous.best': reset tries\n") if (inherits(previous.best, "metaMDS")) previous.best$tries <- 0 } } else { ## no previous.best: start with cmdscale s0 <- switch(engine, "monoMDS" = monoMDS(dist, y = cmdscale(dist, k = k), k = k, maxit = maxit, ...), "isoMDS" = isoMDS(dist, k = k, trace = isotrace, maxit = maxit)) bestry <- 0 trybase <- 0 } if (trace) cat("Run 0 stress", s0$stress, "\n") if (monotrace) monostop(s0) tries <- 0 ## Prepare for parallel processing if (is.null(parallel)) parallel <- 1 hasClus <- inherits(parallel, "cluster") isParal <- hasClus || parallel > 1 isMulticore <- .Platform$OS.type == "unix" && !hasClus if (isParal && !isMulticore && !hasClus) { parallel <- makeCluster(parallel) clusterEvalQ(parallel, library(vegan)) } ## get the number of clusters if (inherits(parallel, "cluster")) nclus <- length(parallel) else nclus <- parallel ## proper iterations while(tries < try || tries < trymax && converged == 0) { init <- replicate(nclus, initMDS(dist, k = k)) if (nclus > 1) isotrace <- FALSE if (isParal) { if (isMulticore) { stry <- mclapply(1:nclus, function(i) switch(engine, "monoMDS" = monoMDS(dist, init[,,i], k = k, maxit = maxit, ...), "isoMDS" = isoMDS(dist, init[,,i], k = k, maxit = maxit, tol = 1e-07, trace = isotrace)), mc.cores = parallel) } else { stry <- parLapply(parallel, 1:nclus, function(i) switch(engine, "monoMDS" = monoMDS(dist, init[,,i], k = k, maxit = maxit, ...), "isoMDS" = isoMDS(dist, init[,,i], k = k, maxit = maxit, tol = 1e-07, trace = isotrace))) } } else { stry <- list(switch(engine, "monoMDS" = monoMDS(dist, init[,,1], k = k, maxit = maxit, ...), "isoMDS" = isoMDS(dist, init[,,1], k = k, maxit = maxit, tol = 1e-07, trace = isotrace))) } ## analyse results of 'nclus' tries for (i in 1:nclus) { tries <- tries + 1 if (trace) cat("Run", tries, "stress", stry[[i]]$stress, "\n") if (trace && engine == "monoMDS") stopcoz[stry[[i]]$icause] <- stopcoz[stry[[i]]$icause] + 1L if (monotrace) monostop(stry[[i]]) if ((s0$stress - stry[[i]]$stress) > -EPS) { pro <- procrustes(s0, stry[[i]], symmetric = TRUE) if (plot && k > 1) plot(pro) if (stry[[i]]$stress < s0$stress) { s0 <- stry[[i]] ## New best solution has not converged unless ## proved later converged <- 0 bestry <- tries + trybase if (trace) cat("... New best solution\n") } summ <- summary(pro) if (trace) cat("... Procrustes: rmse", summ$rmse, " max resid", max(summ$resid), "\n") if (summ$rmse < RMSELIM && max(summ$resid) < RESLIM) { if (trace) cat("... Similar to previous best\n") converged <- converged + 1 } } flush.console() } } if (trace) { if (converged > 0) cat("*** Best solution repeated", converged, "times\n") else if (engine == "monoMDS") { cat(sprintf( "*** Best solution was not repeated -- %s stopping criteria:\n", engine)) for (i in seq_along(stopcoz)) if (stopcoz[i] > 0) cat(sprintf("%6d: %s\n", stopcoz[i], monomsg[i])) } } ## stop socket cluster if (isParal && !isMulticore && !hasClus) stopCluster(parallel) if (!missing(previous.best) && inherits(previous.best, "metaMDS")) { tries <- tries + previous.best$tries } out <- s0 out$ndim = k out$data <- attr(dist, "commname") out$distance <- attr(dist, "method") out$converged <- converged out$tries <- tries out$bestry <- bestry out$engine <- engine out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/metaMDSiter.R
"metaMDSredist" <- function(object, ...) { if (!inherits(object, "metaMDS")) stop("Needs a metaMDS result object") call <- object$call call[[1]] <- as.name("metaMDSdist") eval(call, parent.frame()) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/metaMDSredist.R
`model.frame.cca` <- function (formula, ...) { call <- formula$call m <- match(c("formula", "data", "na.action", "subset"), names(call), 0) call <- call[c(1, m)] ## did we succeed? Fails if we have no formula, in prc and if ## there was no data= argument if (is.null(call$data)) stop("no sufficient information to reconstruct model frame") ## subset must be evaluated before ordiParseFormula if (!is.null(call$subset)) call$subset <- formula$subset if (is.null(call$na.action)) call$na.action <- na.pass data <- eval(call$data, environment(call$formula), .GlobalEnv) out <- ordiParseFormula(call$formula, data, na.action = call$na.action, subset = call$subset) mf <- out$modelframe attr(mf, "terms") <- out$terms.expand if (!is.null(out$na.action)) attr(mf, "na.action") <- out$na.action mf }
/scratch/gouwar.j/cran-all/cranData/vegan/R/model.frame.cca.R
`model.matrix.cca` <- function(object, ...) { X <- Z <- NULL w <- 1/sqrt(object$rowsum) if (!is.null(object$pCCA)) Z <- w * qr.X(object$pCCA$QR) if (!is.null(object$CCA)) { X <- qr.X(object$CCA$QR) ## First columns come from Z if (!is.null(Z)) X <- X[, -seq_len(ncol(Z)), drop = FALSE] X <- w * X } m <- list() if (!is.null(Z)) m$Conditions <- Z if (!is.null(X)) m$Constraints <- X if (length(m) == 1) m <- m[[1]] m } `model.matrix.rda` <- function(object, ...) { X <- Z <- NULL if (!is.null(object$pCCA)) Z <- qr.X(object$pCCA$QR) if (!is.null(object$CCA)) { X <- qr.X(object$CCA$QR) if (!is.null(Z)) X <- X[, -seq_len(ncol(Z)), drop=FALSE] } m <- list() if (!is.null(Z)) m$Conditions <- Z if (!is.null(X)) m$Constraints <- X if (length(m) == 1) m <- m[[1]] m }
/scratch/gouwar.j/cran-all/cranData/vegan/R/model.matrix.cca.R
`monoMDS` <- function(dist, y, k = 2, model = c("global", "local", "linear", "hybrid"), threshold = 0.8, maxit = 200, weakties = TRUE, stress = 1, scaling = TRUE, pc = TRUE, smin = 1e-4, sfgrmin = 1e-7, sratmax=0.999999, ...) { ## Check that 'dist' are distances or a symmetric square matrix if (!(inherits(dist, "dist") || ((is.matrix(dist) || is.data.frame(dist)) && isSymmetric(unname(as.matrix(dist)))))) stop("'dist' must be a distance object (class \"dist\") or a symmetric square matrix") if (any(dist < -sqrt(.Machine$double.eps), na.rm = TRUE)) warning("some dissimilarities are negative -- is this intentional?") if (!any(dist > 0)) stop("'dist' cannot be all zero (all points are identical)") ## match.arg model <- match.arg(model) ## save 'dist' attributes to display in print() distmethod <- attr(dist, "method") if (is.null(distmethod)) distmethod <- "unknown" distcall <-attr(dist, "call") if (!is.null(distcall)) distcall <- deparse(distcall) ## dist to mat mat <- as.matrix(dist) nm <- rownames(mat) if (model %in% c("global", "linear")) { ## global NMDS: lower triangle dist <- mat[lower.tri(mat)] iidx <- row(mat)[lower.tri(mat)] jidx <- col(mat)[lower.tri(mat)] ## Remove missing values if (any(nas <- is.na(dist))) { dist <- dist[!nas] iidx <- iidx[!nas] jidx <- jidx[!nas] } ## non-metric/metric: Fortran parameter 'iregn' if (model == "global") iregn <- 1 else iregn <- 2 ngrp <- 1 nobj <- nrow(mat) istart <- 1 } else if (model == "local") { ## local NMDS: whole matrix without the diagonal, and rows in ## a row (hence transpose) mat <- t(mat) ## Get missing values nas <- is.na(mat) ## groups by rows, except missing values rs <- rowSums(!nas) - 1 istart <- cumsum(rs) istart <- c(0, istart[-length(istart)]) + 1 ## Full matrix expect the diagonal dist <- mat[col(mat) != row(mat)] iidx <- col(mat)[col(mat) != row(mat)] # transpose! jidx <- row(mat)[col(mat) != row(mat)] ## Remove missing values if (any(nas)) { nas <- nas[col(mat) != row(mat)] dist <- dist[!nas] iidx <- iidx[!nas] jidx <- jidx[!nas] } iregn <- 1 nobj <- nrow(mat) ngrp <- nobj } else if (model == "hybrid") { ## Hybrid NMDS: two lower triangles, first a complete one, ## then those with dissimilarities below the threshold dist <- mat[lower.tri(mat)] iidx <- row(mat)[lower.tri(mat)] jidx <- col(mat)[lower.tri(mat)] ## Missing values if (any(nas <- is.na(dist))) { dist <- dist[!nas] iidx <- iidx[!nas] jidx <- jidx[!nas] } ## second group: dissimilarities below threshold ngrp <- 2 istart <- c(1, length(dist) + 1) take <- dist < threshold dist <- c(dist, dist[take]) iidx <- c(iidx, iidx[take]) jidx <- c(jidx, jidx[take]) iregn <- 3 nobj <- nrow(mat) } ## ndis: number of >0 dissimilarities (distinct points) ndis <- length(dist) ## starting configuration if (missing(y)) { y <- matrix(runif(nobj*k, -1, 1), nobj, k) ## centre y <- sweep(y, 2, colMeans(y), "-") } ## y to vector y <- as.vector(as.matrix(y)) ## translate R args to Fortran call if (weakties) ities <- 1 else ities <- 2 ## Fortran call -- must quoted because monoMDS has mixed case (or ## can be FIXED) sol <- .Fortran("monoMDS", nobj = as.integer(nobj), nfix=as.integer(0), ndim = as.integer(k), ndis = as.integer(ndis), ngrp = as.integer(ngrp), diss = as.double(dist), iidx = as.integer(iidx), jidx = as.integer(jidx), xinit = as.double(y), istart = as.integer(istart), isform = as.integer(stress), ities = as.integer(ities), iregn = as.integer(iregn), iscal = as.integer(scaling), maxits = as.integer(maxit), sratmx = as.double(sratmax), strmin = as.double(smin), sfgrmn = as.double(sfgrmin), dist = double(ndis), dhat = double(ndis), points = double(k*nobj), stress = double(1), grstress = double(ngrp), iters = integer(1), icause = integer(1)) sol$call <- match.call() sol$model <- model sol$points <- matrix(sol$points, nobj, k) if (pc) sol$points <- prcomp(sol$points)$x attr(sol$points, "pc") <- pc rownames(sol$points) <- nm colnames(sol$points) <- paste("MDS", 1:k, sep="") ## save info on dissimilarities sol$distmethod <- distmethod sol$distcall <- distcall class(sol) <- "monoMDS" sol }
/scratch/gouwar.j/cran-all/cranData/vegan/R/monoMDS.R
`mrpp` <- function (dat, grouping, permutations = 999, distance = "euclidean", weight.type = 1, strata = NULL, parallel = getOption("mc.cores")) { EPS <- sqrt(.Machine$double.eps) classmean <- function(ind, dmat, indls) { sapply(indls, function(x) mean(c(dmat[ind == x, ind == x]), na.rm = TRUE)) } mrpp.perms <- function(ind, dmat, indls, w) { weighted.mean(classmean(ind, dmat, indls), w = w, na.rm = TRUE) } if (inherits(dat, "dist")) dmat <- dat else if ((is.matrix(dat) || is.data.frame(dat)) && isSymmetric(unname(as.matrix(dat)))) { dmat <- dat attr(dmat, "method") <- "user supplied square matrix" } else dmat <- vegdist(dat, method = distance) if (any(dmat < -sqrt(.Machine$double.eps))) stop("dissimilarities must be non-negative") distance <- attr(dmat, "method") dmat <- as.matrix(dmat) diag(dmat) <- NA N <- nrow(dmat) grouping <- factor(grouping) indls <- levels(grouping) ncl <- sapply(indls, function(x) sum(grouping == x)) w <- switch(weight.type, ncl, ncl - 1, ncl * (ncl - 1)/2) classdel <- classmean(grouping, dmat, indls) names(classdel) <- names(ncl) <- indls del <- weighted.mean(classdel, w = w, na.rm = TRUE) E.del <- mean(dmat, na.rm = TRUE) ## 'Classification strength' if weight.type == 1 ## Do not calculate classification strength because there is no ## significance test for it. Keep the item in reserve for ## possible later re-inclusion. CS <- NA permutations <- getPermuteMatrix(permutations, N, strata = strata) if (ncol(permutations) != N) stop(gettextf("'permutations' have %d columns, but data have %d rows", ncol(permutations), N)) control <- attr(permutations, "control") if(nrow(permutations)) { perms <- apply(permutations, 1, function(indx) grouping[indx]) permutations <- ncol(perms) ## Parallel processing if (is.null(parallel)) parallel <- 1 hasClus <- inherits(parallel, "cluster") if (hasClus || parallel > 1) { if(.Platform$OS.type == "unix" && !hasClus) { m.ds <- unlist(mclapply(1:permutations, function(i, ...) mrpp.perms(perms[,i], dmat, indls, w), mc.cores = parallel)) } else { if (!hasClus) { parallel <- makeCluster(parallel) } m.ds <- parCapply(parallel, perms, function(x) mrpp.perms(x, dmat, indls, w)) if (!hasClus) stopCluster(parallel) } } else { m.ds <- apply(perms, 2, function(x) mrpp.perms(x, dmat, indls, w)) } p <- (1 + sum(del + EPS >= m.ds))/(permutations + 1) r2 <- 1 - del/E.del } else { # no permutations m.ds <- p <- r2 <- NA permutations <- 0 } out <- list(call = match.call(), delta = del, E.delta = E.del, CS = CS, n = ncl, classdelta = classdel, Pvalue = p, A = r2, distance = distance, weight.type = weight.type, boot.deltas = m.ds, permutations = permutations, control = control) class(out) <- "mrpp" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/mrpp.R
`mso` <- function (object.cca, object.xy, grain = 1, round.up = FALSE, permutations = 0) { if (inherits(object.cca, "dbrda")) stop("'mso' is not yet implemented for 'dbrda'\ncontact developers or submit a pull request with your code in github") EPS <- sqrt(.Machine$double.eps) if (inherits(object.cca, "mso")) { rm <- which(class(object.cca) == "mso") class(object.cca) <- class(object.cca)[-rm] } object <- object.cca xy <- object.xy N <- nobs(object) if (inherits(object, "rda")) N <- 1 ## we expect xy are coordinates and calculate distances, but a ## swift user may have supplied distances, and we use them. ## However, we won't test for distances in square matrices, but ## treat that as a user mistake and let it go. if (inherits(xy, "dist")) Dist <- xy else Dist <- dist(xy) object$grain <- grain if (round.up) H <- ceiling(Dist/grain) * grain else H <- round(Dist/grain) * grain hmax <- round((max(Dist)/2)/grain) *grain H[H > hmax] <- max(H) object$H <- H H <- as.vector(H) Dist <- sapply(split(Dist, H), mean) object$vario <- data.frame(H = names(table(H)), Dist = Dist, n = as.numeric(table(H))) test <- list() if (is.numeric(object$CCA$rank)) { if (is.numeric(object$pCCA$rank)) { test$pcca <- sapply(split(dist(ordiYbar(object, "pCCA"))^2 * N/2, H), mean) test$cca <- sapply(split(dist(ordiYbar(object,"CCA"))^2 * N/2, H), mean) test$ca <- sapply(split(dist(ordiYbar(object,"CA"))^2 * N/2, H), mean) test$all.cond <- sapply(split(dist(ordiYbar(object, "partial"))^2 * N/2, H), mean) test$se <- sqrt(sapply(split(dist(ordiYbar(object, "partial"))^2 * N/2, H), var)/object$vario$n) object$vario <- cbind(object$vario, All = test$all.cond, Sum = test$ca + test$cca, CA = test$ca, CCA = test$cca, pCCA = test$pcca, se = test$se) } else { test$all <- sapply(split(dist(ordiYbar(object, "partial"))^2 * N/2, H), mean) test$cca <- sapply(split(dist(ordiYbar(object, "CCA"))^2 * N/2, H), mean) test$ca <- sapply(split(dist(ordiYbar(object,"CA"))^2 * N/2, H), mean) test$se <- sqrt(sapply(split(dist(ordiYbar(object, "partial"))^2 * N/2, H), var)/object$vario$n) object$vario <- cbind(object$vario, All = test$all, Sum = test$ca + test$cca, CA = test$ca, CCA = test$cca, se = test$se) } } else { test$ca <- sapply(split(dist(ordiYbar(object, "CA"))^2 * N/2, H), mean) object$vario <- cbind(object$vario, All = test$ca, CA = test$ca) } permat <- getPermuteMatrix(permutations, nobs(object)) nperm <- nrow(permat) if (nperm) { object$H.test <- matrix(0, length(object$H), nrow(object$vario)) for (i in 1:nrow(object$vario)) { object$H.test[, i] <- as.numeric(object$H == object$vario$H[i]) } xdis <- as.matrix(dist(ordiYbar(object, "CA"))^2) ## taking lower triangle is faster than as.dist() because it ## does not set attributes ltri <- lower.tri(xdis) statistic <- abs(cor(as.vector(xdis[ltri]), object$H.test)) permfunc <- function(k) { permvec <- as.vector(xdis[k,k][ltri]) abs(cor(permvec, object$H.test)) } perm <- sapply(1:nperm, function(take) permfunc(permat[take,])) object$vario$CA.signif <- (rowSums(sweep(perm, 1, statistic - EPS, ">=")) + 1)/ (nperm + 1) attr(object$vario, "control") <- attr(permat, "control") } object$call <- match.call() class(object) <- c("mso", class(object)) object }
/scratch/gouwar.j/cran-all/cranData/vegan/R/mso.R
`msoplot` <- function (x, alpha = 0.05, explained = FALSE, ylim = NULL, legend = "topleft", ...) { if (is.data.frame(x$vario)) { vario <- x$vario hasSig <- is.numeric(x$vario$CA.signif) z <- qnorm(alpha/2) if (is.numeric(vario$CA.signif)) { vario <- vario[, -ncol(vario)] } ymax <- max(vario[, -1:-3], na.rm = TRUE) b <- ncol(vario) - 3 label <- c("", "", "", "Total variance", "Explained plus residual", "Residual variance", "Explained variance", "Conditioned variance") ci.lab <- "C.I. for total variance" sign.lab <- if(hasSig) "Sign. autocorrelation" else NULL if (is.numeric(x$CCA$rank)) { if (!explained) b <- b - 1 if (is.numeric(x$vario$se)) b <- b - 1 figmat <- cbind(vario$All + z * vario$se, vario$All - z * vario$se, vario$Sum, vario[, 6:(b + 3)]) matplot(vario$Dist, cbind(0,figmat), type = "n", xlab = "Distance", ylab = "Variance", ylim = ylim, ...) lines(vario$Dist, vario$All + z * vario$se, lty = 1, ...) lines(vario$Dist, vario$All - z * vario$se, lty = 1, ...) lines(vario$Dist, vario$Sum, type = "b", lty = 2, pch = 3, ...) ## Legend legend(legend, legend=c(label[c(2,3:b)+3], ci.lab, sign.lab), lty=c(c(1,2,1,1,1)[2:b], 1, if(hasSig) NA), pch=c(3, (6:(b+3))-6, NA, if(hasSig) 15) ) matlines(vario$Dist, figmat[,-c(1:3)], type = "b", lty = 1, pch = 6:(b+3)-6, ...) text(x = c(vario$Dist), y = par("usr")[3], pos = 3, label = c(vario$n), cex = 0.8, ...) abline(v = max(x$H/2), lty = 3, ...) } else { if (is.null(ylim)) ylim <- c(0, ymax) plot(vario$Dist, vario$All, type = "b", lty = 1, pch = 0, xlab = "Distance", ylab = "Variance", ylim = ylim, ...) abline(h = x$tot.chi, lty = 5, ...) text(x = c(vario$Dist), y = par("usr")[3], pos = 3, label = c(vario$n), cex = 0.8) abline(v = max(x$H)/2, lty = 3, ...) legend(legend, legend=c("Total variance","Global variance estimate", if(hasSig) "Sign. autocorrelation"), lty=c(1,5, if(hasSig) NA), pch = if(hasSig) c(NA,NA,15) else NULL) } } if (hasSig) { a <- c(1:nrow(x$vario))[x$vario$CA.signif < alpha] points(vario$Dist[a], x$vario$CA[a], pch = 15, ...) if (is.numeric(x$CCA$rank)) { inflation <- 1 - weighted.mean(x$vario$CA, x$vario$n)/ weighted.mean(x$vario$CA[-a], x$vario$n[-a]) cat("Error variance of regression model underestimated by", round(inflation * 100, 1), "percent", "\n") } } invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/msoplot.R
multipart <- function (...) { UseMethod("multipart") }
/scratch/gouwar.j/cran-all/cranData/vegan/R/multipart.R
`multipart.default` <- function(y, x, index=c("renyi", "tsallis"), scales = 1, global = FALSE, relative = FALSE, nsimul=99, method = "r2dtable", ...) { if (length(scales) > 1) stop("length of 'scales' must be one") ## evaluate formula lhs <- as.matrix(y) if (missing(x)) x <- cbind(level_1=seq_len(nrow(lhs)), leve_2=rep(1, nrow(lhs))) rhs <- data.frame(x) rhs[] <- lapply(rhs, as.factor) rhs[] <- lapply(rhs, droplevels, exclude = NA) nlevs <- ncol(rhs) if (nlevs < 2) stop("provide at least two-level hierarchy") if (any(rowSums(lhs) == 0)) stop("data matrix contains empty rows") if (any(lhs < 0)) stop("data matrix contains negative entries") if (is.null(colnames(rhs))) colnames(rhs) <- paste("level", seq_len(nlevs), sep="_") tlab <- colnames(rhs) ## check proper design of the model frame l1 <- sapply(rhs, function(z) length(unique(z))) if (!any(sapply(2:nlevs, function(z) l1[z] <= l1[z-1]))) stop("number of levels are inappropriate, check sequence") rval <- list() rval[[1]] <- rhs[,nlevs] nCol <- nlevs - 1 for (i in 2:nlevs) { rval[[i]] <- interaction(rhs[,nCol], rval[[(i-1)]], drop=TRUE) nCol <- nCol - 1 } rval <- as.data.frame(rval[rev(seq_along(rval))]) l2 <- sapply(rval, function(z) length(unique(z))) if (any(l1 != l2)) stop("levels are not perfectly nested") ## aggregate response matrix fullgamma <-if (nlevels(rhs[,nlevs]) == 1) TRUE else FALSE # if (!fullgamma && !global) # warning("gamma diversity value might be meaningless") ftmp <- vector("list", nlevs) for (i in seq_len(nlevs)) { ftmp[[i]] <- as.formula(paste("~", tlab[i], "- 1")) } ## is there burnin/thin in ... ? burnin <- if (is.null(list(...)$burnin)) 0 else list(...)$burnin thin <- if (is.null(list(...)$thin)) 1 else list(...)$thin ## evaluate other arguments index <- match.arg(index) divfun <- switch(index, "renyi" = function(x) renyi(x, scales=scales, hill = TRUE), "tsallis" = function(x) tsallis(x, scales=scales, hill = TRUE)) ## cluster membership determination nrhs <- rhs nrhs <- sapply(nrhs, as.numeric) idcl <- function(i) { h <- nrhs[,i] l <- nrhs[,(i-1)] sapply(unique(l), function(i) h[l==i][1]) } id <- lapply(2:nlevs, idcl) ## this is the function passed to oecosimu if (global) { wdivfun <- function(x) { if (fullgamma) { tmp <- lapply(seq_len(nlevs - 1), function(i) t(model.matrix(ftmp[[i]], rhs)) %*% x) tmp[[nlevs]] <- matrix(colSums(x), nrow = 1, ncol = ncol(x)) } else { tmp <- lapply(seq_len(nlevs), function(i) t(model.matrix(ftmp[[i]], rhs)) %*% x) } raw <- sapply(seq_len(nlevs), function(i) divfun(tmp[[i]])) a <- sapply(raw, mean) G <- a[nlevs] b <- sapply(seq_len(nlevs - 1), function(i) G / a[i]) if (relative) b <- b / sapply(raw[seq_len(nlevs - 1)], length) c(a, b) } } else { wdivfun <- function(x) { if (fullgamma) { tmp <- lapply(seq_len(nlevs-1), function(i) t(model.matrix(ftmp[[i]], rhs)) %*% x) tmp[[nlevs]] <- matrix(colSums(x), nrow = 1, ncol = ncol(x)) } else { tmp <- lapply(seq_len(nlevs), function(i) t(model.matrix(ftmp[[i]], rhs)) %*% x) } a <- sapply(seq_len(nlevs), function(i) divfun(tmp[[i]])) am <- lapply(seq_len(nlevs - 1), function(i) { sapply(seq_along(unique(id[[i]])), function(ii) { mean(a[[i]][id[[i]]==ii]) }) }) b <- lapply(seq_len(nlevs - 1), function(i) a[[(i+1)]] / am[[i]]) bmax <- lapply(id, function(i) table(i)) if (relative) b <- lapply(seq_len(nlevs - 1), function(i) b[[i]] / bmax[[i]]) c(sapply(a, mean), sapply(b, mean)) } } if (nsimul > 0) { sim <- oecosimu(lhs, wdivfun, method = method, nsimul=nsimul, burnin=burnin, thin=thin) } else { sim <- wdivfun(lhs) tmp <- rep(NA, length(sim)) sim <- list(statistic = sim, oecosimu = list(z = tmp, pval = tmp, method = NA, statistic = sim)) } nam <- c(paste("alpha", seq_len(nlevs - 1), sep="."), "gamma", paste("beta", seq_len(nlevs - 1), sep=".")) names(sim$statistic) <- attr(sim$oecosimu$statistic, "names") <- nam call <- match.call() call[[1]] <- as.name("multipart") attr(sim, "call") <- call attr(sim$oecosimu$simulated, "index") <- index attr(sim$oecosimu$simulated, "scales") <- scales attr(sim$oecosimu$simulated, "global") <- global attr(sim, "n.levels") <- nlevs attr(sim, "terms") <- tlab attr(sim, "model") <- rhs class(sim) <- c("multipart", class(sim)) sim }
/scratch/gouwar.j/cran-all/cranData/vegan/R/multipart.default.R
`multipart.formula` <- function(formula, data, index=c("renyi", "tsallis"), scales = 1, global = FALSE, relative = FALSE, nsimul=99, method = "r2dtable", ...) { ## evaluate formula if (missing(data)) data <- parent.frame() tmp <- hierParseFormula(formula, data) ## run simulations sim <- multipart.default(tmp$lhs, tmp$rhs, index = index, scales = scales, global = global, relative = relative, nsimul = nsimul, method = method, ...) call <- match.call() call[[1]] <- as.name("multipart") attr(sim, "call") <- call sim }
/scratch/gouwar.j/cran-all/cranData/vegan/R/multipart.formula.R
### Multiple-site dissimilarity indices (Sorensen & Jaccard) and their ### decomposition into "turnover" and "nestedness" following Baselga ### (Global Ecology & Biogeography 19, 134-143; 2010). Implemented as ### nestedness functions and directly usable in oecosimu(). `nestedbetasor` <- function(comm) { beta <- betadiver(comm, method = NA) b <- beta$b c <- beta$c diffbc <- sum(abs(b-c)) sumbc <- sum(b+c) bmin <- sum(pmin(b, c)) a <- sum(comm > 0) - sum(colSums(comm) > 0) simpson <- bmin/(bmin + a) nest <- a/(bmin + a) * diffbc/(2*a + sumbc) sorensen <- sumbc/(2*a + sumbc) c(turnover = simpson, nestedness = nest, sorensen = sorensen) } `nestedbetajac` <- function(comm) { beta <- betadiver(comm, method = NA) b <- beta$b c <- beta$c diffbc <- sum(abs(b-c)) sumbc <- sum(b+c) bmin <- sum(pmin(b, c)) a <- sum(comm > 0) - sum(colSums(comm) > 0) simpson <- 2*bmin/(2*bmin + a) nest <- a/(2*bmin + a) * diffbc/(a + sumbc) jaccard <- sumbc/(a + sumbc) c(turnover = simpson, nestedness = nest, jaccard = jaccard) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/nestedbetasor.R
"nestedchecker" <- function(comm) { cb <- sum(designdist(comm, "(A-J)*(B-J)", "binary")) sppairs <- ncol(comm)*(ncol(comm)-1)/2 out <- list("C.score" = cb/sppairs, statistic = cb) names(out$statistic) <- "checkerboards" class(out) <- "nestedchecker" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/nestedchecker.R
`nesteddisc` <- function(comm, niter = 200) { ## The original discrepancy method orders columns by frequencies, ## but does not consider ties. The current function tries to order ## tied values to minimize the discrepancy either by complete ## enumeration or with a larger number of ties using simulated ## annealing. NALL: max no. of tied items for NALL! complete ## enumeration ## starting values and CONSTANTS NALL <- 7 allperm <- factorial(NALL) ties <- FALSE ## Code comm <- ifelse(comm > 0, 1, 0) cs <- colSums(comm) k <- rev(order(cs)) ## initial order cs <- cs[k] comm <- comm[, k] ## run lengths: numbers of tied values le <- rle(cs)$lengths cle <- c(0, cumsum(le)) x <- seq(along=cs) ## Range of row sums: only swaps between these have an effect rs <- range(rowSums(comm)) ## Function to evaluate discrepancy FUN <- function(x) sum(comm[col(comm)[,x] <= rowSums(comm)] == 0) Ad <- FUN(x) ## Go through all le-items and permute ties. Function shuffleSet ## is in permute package, and its minperm argument triggers ## complete enumeration for no. of ties <= NALL!. for (i in seq_along(le)) { if (le[i] > 1) { take <- x idx <- seq_len(le[i]) + cle[i] ## Can swaps influence discrepancy? if (idx[1] > rs[2] || idx[le[i]] < rs[1]) next perm <- shuffleSet(le[i], niter, control = how(minperm = allperm), quietly = TRUE) ## maxperm is a double -- needs EPS -0.5 if ((attr(perm, "control")$maxperm - 0.5) > niter) ties <- TRUE perm <- matrix(perm, ncol = le[i]) + cle[i] vals <- sapply(1:nrow(perm), function(j) { take[idx] <- perm[j,] FUN(take) }) jmin <- which.min(vals) if (vals[jmin] < Ad) { x[idx] <- perm[jmin,] Ad <- vals[jmin] } } } out <- list(statistic=Ad, ties = ties, order = k[x]) names(out$statistic) <- "discrepancy" class(out) <- "nesteddisc" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/nesteddisc.R
"nestedn0" <- function(comm) { comm <- ifelse(comm > 0, 1, 0) R <- rowSums(comm) spmin <- apply(comm, 2, function(x) min((x*R)[x > 0])) n0 <- spmin for (i in 1:ncol(comm)) n0[i] <- sum(comm[,i] == 0 & R > spmin[i]) out <- list(spmin = spmin, n0 = n0, statistic = sum(n0)) names(out$statistic) <- "N0" class(out) <- "nestedn0" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/nestedn0.R
`nestednodf` <- function(comm, order = TRUE, weighted = FALSE, wbinary = FALSE) { bin.comm <- ifelse(comm > 0, 1, 0) rfill <- rowSums(bin.comm) cfill <- colSums(bin.comm) if (!weighted) comm <- bin.comm if (order) { if (weighted) { rgrad <- rowSums(comm) cgrad <- colSums(comm) rorder <- order(rfill, rgrad, decreasing = TRUE) corder <- order(cfill, cgrad, decreasing = TRUE) } else { rorder <- order(rfill, decreasing = TRUE) corder <- order(cfill, decreasing = TRUE) } comm <- comm[rorder, corder] rfill <- rfill[rorder] cfill <- cfill[corder] } nr <- NROW(comm) nc <- NCOL(comm) fill <- sum(rfill)/prod(dim(comm)) N.paired.rows <- numeric(nr * (nr - 1)/2) N.paired.cols <- numeric(nc * (nc - 1)/2) counter <- 0 for (i in 1:(nr - 1)) { first <- comm[i, ] for (j in (i + 1):nr) { counter <- counter + 1 if (rfill[i] <= rfill[j] || any(rfill[c(i, j)] == 0)) next if (weighted) { second <- comm[j, ] if (!wbinary) N.paired.rows[counter] <- sum(first - second > 0 & second > 0)/sum(second > 0) else N.paired.rows[counter] <- sum(first - second >= 0 & second > 0)/sum(second > 0) } else { N.paired.rows[counter] <- sum(first + comm[j, ] == 2)/rfill[j] } } } counter <- 0 for (i in 1:(nc - 1)) { first <- comm[, i] for (j in (i + 1):nc) { counter <- counter + 1 if (cfill[i] <= cfill[j] || any(cfill[c(i, j)] == 0)) next if (weighted) { second <- comm[, j] if (!wbinary) N.paired.cols[counter] <- sum(first - second > 0 & second > 0)/sum(second > 0) else N.paired.cols[counter] <- sum(first - second >= 0 & second > 0)/sum(second > 0) } else { N.paired.cols[counter] <- sum(first + comm[, j] == 2)/cfill[j] } } } N.columns <- mean(N.paired.cols) * 100 N.rows <- mean(N.paired.rows) * 100 NODF <- (sum(c(N.paired.rows, N.paired.cols)) * 100)/ ((nc * (nc - 1)/2) + (nr * (nr - 1)/2)) out <- list(comm = comm, fill = fill, statistic = c(N.columns = N.columns, N.rows = N.rows, NODF = NODF)) class(out) <- "nestednodf" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/nestednodf.R
`nestedtemp` <- function(comm, ...) { ## J Biogeogr 33, 924-935 (2006) says that Atmar & Patterson try ## to pack presences and absence to minimal matrix temperature, ## and the following routines try to reproduce the (partly verbal) ## description. Index s should pack ones, and index t should pack ## zeros, and the final ordering should be "a compromise". colpack <- function(x, rr) { ind <- matrix(rep(rr, ncol(x)), nrow=nrow(x)) s <- -colSums((x*ind)^2) t <- -colSums((nrow(x) - (1-x)*ind + 1)^2) st <- rank(s+t, ties.method = "random") st } rowpack <- function(x, cr) { ind <- matrix(rep(cr, each=nrow(x)), nrow=nrow(x)) s <- -rowSums((x*ind)^2) t <- -rowSums((ncol(x) - (1-x)*ind + 1)^2) st <- rank(s+t, ties.method = "random") st } comm <- ifelse(comm > 0, 1, 0) ## Start with columns, expect if nrow > ncol if (ncol(comm) >= nrow(comm)) { i <- rank(-rowSums(comm), ties.method = "average") } else { j <- rank(-colSums(comm), ties.method = "average") i <- rowpack(comm, j) } ## Improve eight times for (k in seq_len(8)) { j <- colpack(comm, i) i <- rowpack(comm, j) } if (ncol(comm) < nrow(comm)) j <- colpack(comm, i) comm <- comm[order(i), order(j)] r <- ppoints(nrow(comm), a=0.5) c <- ppoints(ncol(comm), a=0.5) dis <- matrix(rep(r, ncol(comm)), nrow=nrow(comm)) totdis <- 1 - abs(outer(r, c, "-")) fill <- sum(comm)/prod(dim(comm)) ## Fill line as defined in J Biogeogr by solving an integral of ## the fill function fillfun <- function(x, p) 1 - (1-(1-x)^p)^(1/p) intfun <- function(p, fill) integrate(fillfun, lower=0, upper=1, p=p)$value - fill ## 'p' will depend on 'fill', and fill = 0.0038 correspond to p = ## 20, and we may need to extend the bracket. sol <- uniroot(intfun, c(0,20), fill=fill, extendInt = "downX") p <- sol$root ## row coordinates of the fill line for all matrix entries out <- matrix(0, nrow=length(r), ncol=length(c)) for (i in seq_along(r)) for (j in seq_along(c)) { a <- c[j] - r[i] out[i,j] <- uniroot(function(x, ...) fillfun(x, p) - a -x, c(0,1), p = p)$root } ## Filline x <- seq(0,1,len=51) xline <- fillfun(x, p) smo <- list(x = x, y = xline) u <- (dis - out)/totdis u[u < 0 & comm == 1] <- 0 u[u > 0 & comm == 0] <- 0 u <- u^2 colnames(u) <- colnames(comm) rownames(u) <- rownames(comm) names(r) <- rownames(comm) names(c) <- colnames(comm) temp <- 100*sum(u)/prod(dim(comm))/0.04145 out <- list(comm = comm, u = u, r = r, c = c, p = p, fill=fill, statistic = temp, smooth=smo) names(out$statistic) <- "temperature" class(out) <- "nestedtemp" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/nestedtemp.R
`no.shared` <- function(x) { x <- as.matrix(x) d <- .Call(do_vegdist, x, as.integer(99)) d <- as.logical(d) attr(d, "Size") <- NROW(x) attr(d, "Labels") <- dimnames(x)[[1]] attr(d, "Diag") <- FALSE attr(d, "Upper") <- FALSE attr(d, "method") <- "no.shared" attr(d, "call") <- match.call() class(d) <- "dist" d }
/scratch/gouwar.j/cran-all/cranData/vegan/R/no.shared.R
### R 2.13.0 introduces nobs() method to get the number of ### observations. This file provides methods for vegan classes. `nobs.anova.cca` <- function(object, ...) NA `nobs.betadisper` <- function(object, ...) length(object$distances) `nobs.cca` <- function(object, ...) max(NROW(object$pCCA$u), NROW(object$CCA$u), NROW(object$CA$u)) `nobs.CCorA` <- function(object, ...) NROW(object$Cy) `nobs.decorana` <- function(object, ...) NROW(object$rproj) `nobs.isomap` <- function(object, ...) NROW(object$points) `nobs.metaMDS` <- function(object, ...) NROW(object$points) `nobs.pcnm` <- function(object, ...) NROW(object$vectors) `nobs.procrustes` <- function(object, ...) NROW(object$X) `nobs.rad` <- function(object, ...) length(object$y) `nobs.varpart` <- function(object, ...) object$part$n `nobs.wcmdscale` <- function(object, ...) NROW(object$points)
/scratch/gouwar.j/cran-all/cranData/vegan/R/nobs.R
## this thing creates an environment ## the whole point is to create all possible inputs for ## commsim functions only once and reuse them as necessary ## also helps keeping track of updating process for sequential algorithms ## method$mode can be evaluated and use storage mode accordingly `nullmodel` <- function(x, method) { x <- as.matrix(x) if (is.null(dim(x)) || length(dim(x)) != 2L) stop("'x' must be a matrix-like object") if (any(is.na(x))) stop("'NA' values not allowed") if (any(x<0)) stop("negative values not allowed") method <- make.commsim(method) if (method$binary) x <- ifelse(x > 0, 1L, 0L) int <- method$mode == "integer" if (int && abs(sum(x) - sum(as.integer(x))) > 10^-6) stop("non-integer values not allowed") if (int) x <- round(x, 0) # round up to closest integer storage.mode(x) <- method$mode out <- list( data=x, nrow=as.integer(dim(x)[1L]), ncol=as.integer(dim(x)[2L]), rowSums=rowSums(x), colSums=colSums(x), rowFreq=as.integer(rowSums(x > 0)), colFreq=as.integer(colSums(x > 0)), totalSum=ifelse(int, as.integer(sum(x)), as.double(sum(x))), fill=as.integer(sum(x > 0)), commsim=method, state=if (method$isSeq) x else NULL, iter=if (method$isSeq) as.integer(0L) else NULL ) # storage.mode(out$x) <- method$mode storage.mode(out$rowSums) <- method$mode storage.mode(out$colSums) <- method$mode out <- list2env(out, parent=emptyenv()) class(out) <- c("nullmodel", "environment") # class(out) <- "nullmodel" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/nullmodel.R
`oecosimu` <- function(comm, nestfun, method, nsimul=99, burnin=0, thin=1, statistic = "statistic", alternative = c("two.sided", "less", "greater"), batchsize = NA, parallel = getOption("mc.cores"), ...) { alternative <- match.arg(alternative) nestfun <- match.fun(nestfun) if (length(statistic) > 1) stop("only one 'statistic' is allowed") if (!is.na(batchsize)) batchsize <- batchsize * 1024 * 1024 applynestfun <- function(x, fun = nestfun, statistic = "statistic", ...) { tmp <- fun(x, ...) if (is.list(tmp)) tmp[[statistic]] else tmp } chains <- NULL if (inherits(comm, "simmat")) { x <- comm method <- attr(x, "method") nsimul <- dim(x)[3] if (nsimul == 1) stop(gettextf("only one simulation in '%s'", deparse(substitute(comm)))) comm <- attr(comm, "data") #thin <- attr(comm, "thin") burnin <- attr(x, "start") - attr(x, "thin") chains <- attr(x, "chains") simmat_in <- TRUE } else { simmat_in <- FALSE if (inherits(comm, "nullmodel")) { nm <- comm comm <- comm$data } else { nm <- nullmodel(comm, method) if (nm$commsim$binary) { ## sometimes people do not realize that null model ## makes their data binary if (max(abs(comm - nm$data)) > 0.1) warning("nullmodel transformed 'comm' to binary data") comm <- nm$data } } method <- nm$commsim$method } ## Check the number of batches needed to run the requested number ## of simulations without exceeding arg 'batchsize', and find the ## size of each batch. if (!simmat_in && !is.na(batchsize)) { commsize <- object.size(comm) totsize <- commsize * nsimul if (totsize > batchsize) { nbatch <- ceiling(unclass(totsize/batchsize)) batches <- diff(round(seq(0, nsimul, by = nsimul/nbatch))) } else { nbatch <- 1 } } else { nbatch <- 1 } if (nbatch == 1) batches <- nsimul ind <- nestfun(comm, ...) indstat <- if (is.list(ind)) ind[[statistic]] else ind ## burnin of sequential models if (!simmat_in && nm$commsim$isSeq) { ## estimate thinning for "tswap" (trial swap) if (nm$commsim$method == "tswap") { checkbrd <-sum(designdist(comm, "(J-A)*(J-B)", "binary")) M <- nm$ncol N <- nm$nrow checkbrd <- M * (M - 1) * N * (N - 1)/4/checkbrd thin <- round(thin * checkbrd) burnin <- round(burnin * checkbrd) } if (burnin > 0) nm <- update(nm, burnin) } ## start with empty simind simind <- NULL ## Go to parallel processing if 'parallel > 1' or 'parallel' could ## be a pre-defined socket cluster or 'parallel = NULL'. if (is.null(parallel)) parallel <- 1 hasClus <- inherits(parallel, "cluster") if (hasClus || parallel > 1) { if(.Platform$OS.type == "unix" && !hasClus) { for (i in seq_len(nbatch)) { ## simulate if no simmat_in if(!simmat_in) x <- simulate(nm, nsim = batches[i], thin = thin) tmp <- mclapply(seq_len(batches[i]), function(j) applynestfun(x[,,j], fun=nestfun, statistic = statistic, ...), mc.cores = parallel) simind <- cbind(simind, do.call(cbind, tmp)) } } else { ## if hasClus, do not set up and stop a temporary cluster if (!hasClus) { parallel <- makeCluster(parallel) ## make vegan functions available: others may be unavailable clusterEvalQ(parallel, library(vegan)) } for(i in seq_len(nbatch)) { if (!simmat_in) x <- simulate(nm, nsim = batches[i], thin = thin) simind <- cbind(simind, parApply(parallel, x, 3, function(z) applynestfun(z, fun = nestfun, statistic = statistic, ...))) } if (!hasClus) stopCluster(parallel) } } else { for(i in seq_len(nbatch)) { ## do not simulate if x was already a simulation if(!simmat_in) x <- simulate(nm, nsim = batches[i], thin = thin) simind <- cbind(simind, apply(x, 3, applynestfun, fun = nestfun, statistic = statistic, ...)) } } simind <- matrix(simind, ncol = nsimul) if (attr(x, "isSeq")) { attr(simind, "thin") <- attr(x, "thin") attr(simind, "burnin") <- burnin attr(simind, "chains") <- chains } sd <- apply(simind, 1, sd, na.rm = TRUE) means <- rowMeans(simind, na.rm = TRUE) z <- (indstat - means)/sd if (any(sd < sqrt(.Machine$double.eps))) z[sd < sqrt(.Machine$double.eps)] <- 0 ## results can be integers or real: comparisons differ if (is.integer(indstat) && is.integer(simind)) { pless <- rowSums(indstat >= simind, na.rm = TRUE) pmore <- rowSums(indstat <= simind, na.rm = TRUE) } else { EPS <- sqrt(.Machine$double.eps) pless <- rowSums(indstat + EPS >= simind, na.rm = TRUE) pmore <- rowSums(indstat - EPS <= simind, na.rm = TRUE) } if (any(is.na(simind))) { warning("some simulated values were NA and were removed") nsimul <- nsimul - rowSums(is.na(simind)) } p <- switch(alternative, two.sided = 2*pmin(pless, pmore), less = pless, greater = pmore) p <- pmin(1, (p + 1)/(nsimul + 1)) ## ADDITION: if z is NA then it is not correct to calculate p values ## try e.g. oecosimu(dune, sum, "permat") if (any(is.na(z))) p[is.na(z)] <- NA ## take care that statistics have name, or some support functions ## can fail if (is.null(names(indstat))) { if (length(indstat) == 1) names(indstat) <- statistic else if (length(indstat) <= length(letters)) names(indstat) <- letters[seq_along(indstat)] else names(indstat) <- paste0("stat", seq_along(indstat)) } oecosimu <- list(z = z, means = means, pval = p, simulated=simind, method=method, statistic = indstat, alternative = alternative, isSeq = attr(x, "isSeq")) out <- list(statistic = ind, oecosimu = oecosimu) attr(out, "call") <- match.call() class(out) <- "oecosimu" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/oecosimu.R
### The constrained ordination methods cca, rda, capscale & dbrda are ### very similar. Their main difference is the init of dependent ### matrix and after that the partializing, constraining and residual ### steps are very similar to each other. This file provides functions ### that can analyse any classic method, the only difference being the ### attributes of the dependet variable. ### In this file we use convention modelfunction(Y, X, Z) where Y is ### the dependent data set (community), X is the model matrix of ### constraints, and Z is the model matrix of conditions to be ### partialled out. The common outline of the function is: ### ### initX(Y) ### pCCA <- ordPartial(Y, Z) ### CCA <- ordConstrain(Y, X, Z) ### CA <- ordResid(Y) ### ### The init step sets up the dependent data Y and sets up its ### attributes that control how it will be handled at later ### stage. Each of the later stages modifies Y and returns results of ### its analysis. The handling of the function is mainly similar, but ### there is some variation depending on the attributes of Y. ### THE USAGE ### Function prototype is ordConstrained(Y, X=NULL, Z=NULL, method), ### where Y is the dependent community data set, X is the model matrix ### of constraints, Z the model matrix of conditions, method is "cca", ### "rda", "capscale" or "dbrda" (the last two may not work, and ### "capscale" may not work in the way you assume). The function ### returns a large subset of correspoding constrained ordination ### method. For instance, with method = "dbrda", the result is mainly ### correct, but it differs so much from the current dbrda that it ### cannot be printed cleanly. ### THE INIT METHODS ### The init methods transform the dependent data specifically to the ### particular method and set up attributes that will control further ### processing of Y. The process critical attributes are set up in ### UPPER CASE to make the if-statements stand out in later analysis. `initPCA` <- function(Y, scale = FALSE) { Y <- as.matrix(Y) Y <- scale(Y, scale = scale) if (scale && any(is.nan(Y))) Y[is.nan(Y)] <- 0 ## we want models based on variance or correlations -- this will ## break methods depending on unscaled Xbar (and which do this ## very same scaling internally) with scale = FALSE. Y <- Y / sqrt(nrow(Y) - 1) attr(Y, "METHOD") <- "PCA" Y } `initCAP` <- function(Y) { Y <- as.matrix(Y) Y <- scale(Y, scale = FALSE) attr(Y, "METHOD") <- "CAPSCALE" Y } `initCA` <- function(Y) { Y <- as.matrix(Y) tot <- sum(Y) Y <- Y/tot rw <- rowSums(Y) cw <- colSums(Y) rc <- outer(rw, cw) Y <- (Y - rc)/sqrt(rc) attr(Y, "tot") <- tot attr(Y, "RW") <- rw attr(Y, "CW") <- cw attr(Y, "METHOD") <- "CA" Y } `initDBRDA` <- function(Y) { ## check Y <- as.matrix(Y) dims <- dim(Y) if (dims[1] != dims[2] || !isSymmetric(unname(Y))) stop("input Y must be distances or a symmetric square matrix") ## transform Y <- -0.5 * GowerDblcen(Y^2) attr(Y, "METHOD") <- "DISTBASED" Y } ### COMMON HEADER INFORMATION FOR ORDINATION MODELS `ordHead`<- function(Y) { method <- attr(Y, "METHOD") headmethod <- switch(method, "CA" = "cca", "PCA" = "rda", "CAPSCALE" = "capscale", "DISTBASED" = "dbrda") if (method == "DISTBASED") totvar <- sum(diag(Y)) else totvar <- sum(Y^2) head <- list("tot.chi" = totvar, "Ybar" = Y, "method" = headmethod) if (method == "CA") head <- c(list("grand.total" = attr(Y, "tot"), "rowsum" = attr(Y, "RW"), "colsum" = attr(Y, "CW")), head) else if (method == "PCA") head <- c(list("colsum" = sqrt(colSums(Y^2))), head) head } ### THE PARTIAL MODEL `ordPartial` <- function(Y, Z) { ZERO <- sqrt(.Machine$double.eps) ## attributes DISTBASED <- attr(Y, "METHOD") == "DISTBASED" RW <- attr(Y, "RW") ## centre Z if (!is.null(RW)) { envcentre <- apply(Z, 2, weighted.mean, w = RW) Z <- scale(Z, center = envcentre, scale = FALSE) Z <- sweep(Z, 1, sqrt(RW), "*") } else { envcentre <- colMeans(Z) Z <- scale(Z, center = envcentre, scale = FALSE) } ## QR decomposition Q <- qr(Z) if (Q$rank == 0) # nothing partialled out return(list(Y = Y, result = NULL)) ## partialled out variation as a trace of Yfit Yfit <- qr.fitted(Q, Y) if (DISTBASED) { Yfit <- qr.fitted(Q, t(Yfit)) totvar <- sum(diag(Yfit)) } else { totvar <- sum(Yfit^2) } if (totvar < ZERO) totvar <- 0 ## residuals of Y Y <- qr.resid(Q, Y) if (DISTBASED) Y <- qr.resid(Q, t(Y)) ## result object like in current cca, rda result <- list( rank = if (totvar > 0) Q$rank else 0, tot.chi = totvar, QR = Q, envcentre = envcentre) list(Y = Y, result = result) } ### THE CONSTRAINTS `ordConstrain` <- function(Y, X, Z) { ## attributes & constants DISTBASED <- attr(Y, "METHOD") == "DISTBASED" RW <- attr(Y, "RW") CW <- attr(Y, "CW") ZERO <- sqrt(.Machine$double.eps) ## combine conditions and constraints if necessary if (!is.null(Z)) { X <- cbind(Z, X) zcol <- ncol(Z) } else { zcol <- 0 } ## centre if (!is.null(RW)) { envcentre <- apply(X, 2, weighted.mean, w = RW) X <- scale(X, center = envcentre, scale = FALSE) X <- sweep(X, 1, sqrt(RW), "*") } else { envcentre <- colMeans(X) X <- scale(X, center = envcentre, scale = FALSE) } ## QR Q <- qr(X) ## we need to see how much rank grows over rank of conditions rank <- sum(Q$pivot[seq_len(Q$rank)] > zcol) ## nothing explained (e.g., constant constrain) if (rank == 0) return(list(Y = Y, result = NULL)) ## check for aliased terms if (length(Q$pivot) > Q$rank) alias <- colnames(Q$qr)[-seq_len(Q$rank)] else alias <- NULL ## kept constraints and their means kept <- seq_along(Q$pivot) <= Q$rank & Q$pivot > zcol if (zcol > 0) envcentre <- envcentre[-seq_len(zcol)] ## eigen solution Yfit <- qr.fitted(Q, Y) if (DISTBASED) { Yfit <- qr.fitted(Q, t(Yfit)) sol <- eigen(Yfit, symmetric = TRUE) lambda <- sol$values u <- sol$vectors } else { sol <- svd(Yfit) lambda <- sol$d^2 u <- sol$u v <- sol$v } ## handle zero eigenvalues and negative eigenvalues zeroev <- abs(lambda) < max(ZERO, ZERO * lambda[1L]) if (any(zeroev)) { lambda <- lambda[!zeroev] u <- u[, !zeroev, drop = FALSE] if (!DISTBASED) v <- v[, !zeroev, drop = FALSE] } posev <- lambda > 0 ## wa scores if (DISTBASED) { wa <- Y %*% u[, posev, drop = FALSE] %*% diag(1/lambda[posev], sum(posev)) v <- matrix(NA, 0, sum(posev)) } else { wa <- Y %*% v %*% diag(1/sqrt(lambda), sum(posev)) } ## biplot scores: basically these are cor(X, u), but cor() would ## re-centre X and u in CCA, and therefore we need the following ## (which also is faster) xx <- X[, Q$pivot[kept], drop = FALSE] bp <- (1/sqrt(colSums(xx^2))) * crossprod(xx, u[, posev, drop=FALSE]) ## de-weight if (!is.null(RW)) { u <- sweep(u, 1, sqrt(RW), "/") if (!anyNA(wa)) { wa <- sweep(wa, 1, sqrt(RW), "/") } } if (!is.null(CW) && nrow(v)) { v <- sweep(v, 1, sqrt(CW), "/") } ## set names axnam <- paste0(switch(attr(Y, "METHOD"), "PCA" = "RDA", "CA" = "CCA", "CAPSCALE" = "CAP", "DISTBASED" = "dbRDA"), seq_len(sum(posev))) if (DISTBASED && any(!posev)) negnam <- paste0("idbRDA", seq_len(sum(!posev))) else negnam <- NULL dnam <- dimnames(Y) if (any(posev)) names(lambda) <- c(axnam, negnam) if (ncol(u)) dimnames(u) <- list(dnam[[1]], c(axnam, negnam)) if (nrow(v) && ncol(v)) # no rows in DISTBASED dimnames(v) <- list(dnam[[2]], axnam) if (ncol(wa)) # only for posev colnames(wa) <- axnam if (ncol(bp)) # only for posev colnames(bp) <- axnam ## out result <- list( eig = lambda, poseig = if (DISTBASED) sum(posev) else NULL, u = u, v = v, wa = wa, alias = alias, biplot = bp, rank = length(lambda), qrank = rank, tot.chi = sum(lambda), QR = Q, envcentre = envcentre) ## residual of Y Y <- qr.resid(Q, Y) if (DISTBASED) Y <- qr.resid(Q, t(Y)) ## out list(Y = Y, result = result) } ### THE RESIDUAL METHOD ### Finds the unconstrained ordination after (optionally) removing the ### variation that could be explained by partial and constrained ### models. `ordResid` <- function(Y) { ## get attributes DISTBASED <- attr(Y, "METHOD") == "DISTBASED" RW <- attr(Y, "RW") CW <- attr(Y, "CW") ## Ordination ZERO <- sqrt(.Machine$double.eps) if (DISTBASED) { sol <- eigen(Y, symmetric = TRUE) lambda <- sol$values u <- sol$vectors } else { sol <- svd(Y) lambda <- sol$d^2 u <- sol$u v <- sol$v } ## handle zero and negative eigenvalues zeroev <- abs(lambda) < max(ZERO, ZERO * lambda[1L]) if (any(zeroev)) { lambda <- lambda[!zeroev] u <- u[, !zeroev, drop = FALSE] if (!DISTBASED) # no v in DISTBASED v <- v[, !zeroev, drop = FALSE] } posev <- lambda > 0 if (DISTBASED) # no species scores in DISTBASED v <- matrix(NA, 0, sum(posev)) ## de-weight if (!is.null(RW)) { u <- sweep(u, 1, sqrt(RW), "/") } if (!is.null(CW) && nrow(v)) { v <- sweep(v, 1, sqrt(CW), "/") } ## set names axnam <- paste0(switch(attr(Y, "METHOD"), "PCA" = "PC", "CA" = "CA", "CAPSCALE" = "MDS", "DISTBASED" = "MDS"), seq_len(sum(posev))) if (DISTBASED && any(!posev)) negnam <- paste0("iMDS", seq_len(sum(!posev))) else negnam <- NULL dnam <- dimnames(Y) if (any(posev)) names(lambda) <- c(axnam, negnam) if (ncol(u)) dimnames(u) <- list(dnam[[1]], c(axnam, negnam)) if (nrow(v) && ncol(v)) # no rows in DISTBASED dimnames(v) <- list(dnam[[2]], axnam) ## out out <- list( "eig" = lambda, "poseig" = if (DISTBASED) sum(posev) else NULL, "u" = u, "v" = v, "rank" = length(lambda), "tot.chi" = sum(lambda)) out } ## The actual function that calls all previous and returns the fitted ## ordination model `ordConstrained` <- function(Y, X = NULL, Z = NULL, method = c("cca", "rda", "capscale", "dbrda", "pass"), arg = FALSE) { method = match.arg(method) partial <- constraint <- resid <- NULL ## init; "pass" returns unchanged Y, presumably from previous init Y <- switch(method, "cca" = initCA(Y), "rda" = initPCA(Y, scale = arg), "capscale" = initCAP(Y), "dbrda" = initDBRDA(Y), "pass" = Y) ## sanity checks for the input if (!is.numeric(Y)) stop("dependent data (community) must be numeric") if (!is.null(X)) { if (!is.numeric(X)) stop("constraints must be numeric or factors") if (nrow(Y) != nrow(X)) stop("dependent data and constraints must have the same number of rows") } if (!is.null(Z)) { if (!is.numeric(Z)) stop("conditions must be numeric or factors") if (nrow(Y) != nrow(Z)) stop("dependent data and conditions must have the same number of rows") } ## header info for the model head <- ordHead(Y) ## Partial if (!is.null(Z) && ncol(Z)) { out <- ordPartial(Y, Z) Y <- out$Y partial <- out$result } ## Constraints if (!is.null(X) && ncol(X)) { out <- ordConstrain(Y, X, Z) Y <- out$Y constraint <- out$result } ## Residuals resid <- ordResid(Y) ## return a CCA object out <- c(head, call = match.call(), list("pCCA" = partial, "CCA" = constraint, "CA" = resid)) class(out) <- switch(attr(Y, "METHOD"), "CA" = "cca", "PCA" = c("rda", "cca"), "CAPSCALE" = c("capscale", "rda", "cca"), "DISTBASED" = c("dbrda", "rda", "cca")) out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordConstrained.R
`orderingKM` <- function(mat) { ### INPUT : ### mat (n x k): n the objects and k the descriptors ### This matrix must be integers and numeric ### And must not be binairy, it is the partition matrix ### output by cascadeKM ### OUTPUT : Ordered matrix ## Uses alternatively the fast USEPOWERALGORITHM provided by Legendre ## et al., or the standard R function cmdscale with matching ## coefficient provided by vegdist.c as method=50. USEPOWERALGORITHM <- TRUE ##Check up if(!is.matrix(mat)) stop("'mat' must be a matrix") if(!is.numeric(mat)) stop("'mat' must be numeric") if(any(is.na(mat))) stop("'NA' value was found in the matrix") if(any(is.infinite(mat))) stop("'Inf' value was found in the matrix") nb.desc=ncol(mat) nb.obj=nrow(mat) scores<-rep(0.0,nb.obj) if (USEPOWERALGORITHM) { scores <- as.vector(.Fortran(orderdata, as.integer(mat), as.integer(nb.obj), as.integer(nb.desc), sc=as.double(scores))$sc) } else { d <- .Call(do_vegdist, as.matrix(mat), as.integer(50)) attr(d, "Size") <- nb.obj attr(d, "Labels") <- dimnames(mat)[[1]] attr(d, "Diag") <- FALSE attr(d, "Upper") <- FALSE attr(d, "method") <- "matching" class(d) <- "dist" scores <- cmdscale(d, k = 1)[,1] } scores <- order(scores) mat[scores,] }
/scratch/gouwar.j/cran-all/cranData/vegan/R/orderingKM.R
`ordiArgAbsorber` <- function(..., shrink, origin, scaling, triangular, display, choices, const, truemean, FUN) match.fun(FUN)(...)
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiArgAbsorber.R
### Scaling of arrows to 'fill' a plot with vectors centred at 'at'. ### Plot dims from 'par("usr")' and arrow heads are in 'x'. `ordiArrowMul` <- function (x, at = c(0,0), fill = 0.75, display, choices = c(1,2), ...) { ## handle x, which we try with scores, but also retain past usage of ## a two column matrix X <- if (is.matrix(x)) { nc <- NCOL(x) if (nc != 2L) { stop("a two-column matrix of coordinates is required") } x } else { if (inherits(x, "envfit")) { scores(x, display = "vectors", ...)[, 1:2, drop = FALSE] } else { scores(x, display = display, choices = choices, ...) } } u <- par("usr") u <- u - rep(at, each = 2) r <- c(range(X[,1], na.rm = TRUE), range(X[,2], na.rm = TRUE)) ## 'rev' takes care of reversed axes like xlim(1,-1) rev <- sign(diff(u))[-2] if (rev[1] < 0) u[1:2] <- u[2:1] if (rev[2] < 0) u[3:4] <- u[4:3] u <- u/r u <- u[is.finite(u) & u > 0] fill * min(u) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiArrowMul.R
### Location of the text at the point of the arrow. 'x' are the ### coordinates of the arrow heads, and 'labels' are the text used to ### label these heads, '...' passes arguments (such as 'cex') to ### strwidth() and strheight(). `ordiArrowTextXY` <- function (x, labels, display, choices = c(1,2), rescale = TRUE, fill = 0.75, at = c(0,0), ...) { ## handle x, which we try with scores, but also retain past usage of ## a two column matrix X <- if (is.matrix(x)) { nc <- NCOL(x) if (nc != 2L) { stop("a two-column matrix of coordinates is required") } x } else { if (inherits(x, "envfit")) { scores(x, display = "vectors", ...)[, 1:2] } else { scores(x, display = display, choices = choices, ...) } if (!rescale) { warning("extracted scores usually need rescaling but you set 'rescale = FALSE' - \nconsider using 'rescale = TRUE', the default") } } ## find multiplier to fill if rescaling if (rescale) { mul <- ordiArrowMul(X, fill = fill, at = at) X <- X * mul } if (missing(labels)) { rnames <- rownames(X) labels <- if (is.null(rnames)) { paste("V", seq_len(NROW(X))) } else { rnames } } w <- strwidth(labels, ...) h <- strheight(labels, ...) ## slope of arrows b <- (X[,2] - at[2]) / (X[,1] - at[1]) ## offset based on string dimensions off <- cbind(sign(X[,1] - at[1]) * (w/2 + h/4), 0.75 * h * sign(X[,2] - at[2])) ## move the centre of the string to the continuation of the arrow for(i in seq_len(nrow(X))) { move <- off[i,2] / b[i] ## arrow points to the top/bottom of the text box if (is.finite(move) && abs(move) <= abs(off[i, 1])) off[i, 1] <- move else { ## arrow points to a side of the text box move <- b[i] * off[i,1] off[i, 2] <- move } } off + X }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiArrowTextXY.R
### A pair of functions to handle na.action = na.exclude in cca and ### rda (and capscale in the future?). Function ordiNAexclude finds ### the WA scores for NA constraints if possible, and puts these into ### ordination object. Function ordiNApredict pads the result scores ### with NA or scores if available. `ordiNAexclude` <- function(x, excluded) { ## Check that there is a na.action of class "exclude" nas <- x$na.action if (is.null(nas)) return(x) ## add a 'residuals' item, because step, add1.default and ## drop1.default use this to check that number of observations ## does not change in sequential fits. x$residuals.zombie <- rep(TRUE, max(0, nrow(x$CA$u))) ## rowsums for CA (in RDA/PCA rowsum = NA) if (!inherits(x, "rda")) x$rowsum.excluded <- rowSums(excluded)/x$grand.total ## Estimate WA scores for NA cases with newdata of excluded ## observations if (is.null(x$pCCA) && inherits(nas, "exclude") && !inherits(x, c("dbrda", "capscale"))) { if (!is.null(x$CCA)) x$CCA$wa.excluded <- predict(x, newdata = excluded, type = "wa", model = "CCA") if (!is.null(x$CA)) x$CA$u.excluded <- predict(x, newdata = excluded, type = "wa", model = "CA") } x } ### Put NA or fitted WA among the scores `ordiNApredict` <- function(omit, x) { ## Only do this if omit is of class "exclude" if (!inherits(omit, "exclude")) return(x) if (!inherits(x, "rda")) { x$rowsum <- napredict(omit, x$rowsum) if (inherits(omit, "exclude")) x$rowsum[omit] <- x$rowsum.excluded } if (!is.null(x$CCA)) { x$CCA$u <- napredict(omit, x$CCA$u) x$CCA$wa <- napredict(omit, x$CCA$wa) if (!is.null(x$CCA$wa.excluded)) x$CCA$wa[omit,] <- x$CCA$wa.excluded } if (!is.null(x$CA)) { x$CA$u <- napredict(omit, x$CA$u) if (!is.null(x$CA$u.excluded)) x$CA$u[omit,] <- x$CA$u.excluded } x }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiNAexclude.R
`ordiParseFormula` <- function (formula, data, xlev = NULL, na.action = na.fail, subset = NULL, X) { if (missing(data)) data <- environment(formula) Terms <- terms(formula, "Condition", data = data) flapart <- fla <- formula <- formula(Terms, width.cutoff = 500) ## distance-based methods (capscale, dbrda) evaluate specdata (LHS ## in formula) within their code, and the handling in ## ordiParseFormula is redundand and can be expensive if (missing(X)) { specdata <- formula[[2]] X <- eval(specdata, environment(formula), enclos=globalenv()) } X <- as.matrix(X) indPartial <- attr(Terms, "specials")$Condition zmf <- ymf <- Y <- Z <- NULL formula[[2]] <- NULL if (!is.null(indPartial)) { partterm <- attr(Terms, "variables")[1 + indPartial] ## paste() needed to combine >500 character deparsed Conditions Pterm <- sapply(partterm, function(x) paste(deparse(x[[2]], width.cutoff=500, backtick = TRUE), collapse=" ")) Pterm <- paste(Pterm, collapse = "+") P.formula <- as.formula(paste("~", Pterm), env = environment(formula)) zlev <- xlev[names(xlev) %in% Pterm] zmf <- if (inherits(data, "environment")) eval(substitute( model.frame(P.formula, na.action = na.pass, xlev = zlev)), envir = data, enclos = .GlobalEnv) else model.frame(P.formula, data, na.action = na.pass, xlev = zlev) partterm <- sapply(partterm, function(x) paste(deparse(x, width.cutoff=500, backtick = TRUE), collapse = " ")) formula <- update(formula, paste("~.-", paste(partterm, collapse = "-"))) flapart <- update(formula, paste(" ~ . +", Pterm)) } if (formula[[2]] == "1" || formula[[2]] == "0") Y <- NULL else { if (exists("Pterm")) xlev <- xlev[!(names(xlev) %in% Pterm)] ymf <- if (inherits(data, "environment")) eval(substitute( model.frame(formula, na.action = na.pass, xlev = xlev)), envir=data, enclos=.GlobalEnv) else model.frame(formula, data, na.action = na.pass, xlev = xlev) } ## Combine condition an constrain data frames if (!is.null(zmf)) { ncond <- NCOL(zmf) if (!is.null(ymf)) mf <- cbind(zmf, ymf) else mf <- zmf } else { ncond <- 0 mf <- ymf } ## Select a subset of data and species if (!is.null(subset)) { subset <- eval(subset, if (inherits(data, "data.frame")) cbind(data, X) else as.data.frame(X), parent.frame(2)) X <- X[subset, , drop = FALSE] if (NROW(mf) > 0) mf <- mf[subset, , drop = FALSE] } ## Get na.action attribute, remove NA and drop unused levels if (NROW(mf) > 0) { ## We need to re-construct model.frame and its formula, and ## for this names with functions must be back-quoted ## (`poly(A1, 2)`, e.g.) with the curren scoping to find the ## variable (A1) later. This happened with formula(mf) in R < ## 3.6.0, but now we must be explicit. mf <- model.frame(as.formula(paste("~", paste(sapply(names(mf), "as.name"), collapse="+"))), mf, xlev = xlev, na.action = na.action, drop.unused.levels = TRUE) nas <- attr(mf, "na.action") ## Check if there are one-level factors after subset and na.action for (i in 1:ncol(mf)) if (is.factor(mf[[i]]) && length(levels(mf[[i]])) <= 1) levels(mf[[i]]) <- c(levels(mf[[i]]), ".ThisVarHasOnly1Level") } else { nas <- NULL } ## Check and remove NA in dependent data if (!is.null(nas)) { excluded <- X[nas, , drop = FALSE] X <- X[-nas,, drop=FALSE] } else { excluded <- NULL } if (ncond > 0) { Z <- model.matrix(P.formula, mf) if (any(colnames(Z) == "(Intercept)")) Z <- Z[, -which(colnames(Z) == "(Intercept)"), drop = FALSE] } if (NROW(mf) > 0) { Y <- model.matrix(formula, mf) ## save assign attribute assign <- attr(Y, "assign") assign <- assign[assign > 0] if (any(colnames(Y) == "(Intercept)")) Y <- Y[, -which(colnames(Y) == "(Intercept)"), drop = FALSE] if (NCOL(Y) == 0) Y <- NULL else attr(Y, "assign") <- assign } X <- as.matrix(X) rownames(X) <- rownames(X, do.NULL = FALSE) colnames(X) <- colnames(X, do.NULL = FALSE) if (!is.null(Y)) { rownames(Y) <- rownames(Y, do.NULL = FALSE) colnames(Y) <- colnames(Y, do.NULL = FALSE) } if (!is.null(Z)) { rownames(Z) <- rownames(Z, do.NULL = FALSE) colnames(Z) <- colnames(Z, do.NULL = FALSE) } list(X = X, Y = Y, Z = Z, terms = terms(fla, width.cutoff = 500), terms.expand = terms(flapart, width.cutoff = 500), modelframe = mf, subset = subset, na.action = nas, excluded = excluded) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiParseFormula.R
### Forward selection to maximize R2.adjusted, but stopping once the ### R2.adjusted of the maximum model ('scope') is exceeded, after ### Blanchet, Legendre & Borcard: Ecology 89, 2623--2623; 2008. `ordiR2step` <- function(object, scope, Pin = 0.05, R2scope = TRUE, permutations = how(nperm=499), trace = TRUE, R2permutations = 1000, ...) { if (is.null(object$terms)) stop("ordination model must be fitted using formula") if (missing(scope)) stop("needs scope") if (inherits(scope, "cca")) scope <- delete.response(formula(scope)) if (!inherits(scope, "formula")) scope <- reformulate(scope) ## Get R2 of the original object if (is.null(object$CCA)) R2.0 <- 0 else R2.0 <- RsquareAdj(object, permutations = R2permutations, ...)$adj.r.squared ## only accepts upper scope if (is.list(scope) && length(scope) <= 2L) scope <- scope$upper if (is.null(scope) || !length(add.scope(object, scope))) stop("needs upper 'scope': no terms can be added") ## Get R2 of the scope if (R2scope) R2.all <- RsquareAdj(update(object, delete.response(formula(scope))), permutations = R2permutations, ...) else R2.all <- list(adj.r.squared = NA) ## Check that the full model can be evaluated if (is.na(R2.all$adj.r.squared) && R2scope) stop("the upper scope cannot be fitted (too many terms?)") R2.all <- R2.all$adj.r.squared ## Collect data to anotab returned as the 'anova' object anotab <- list() ## Step forward and continue as long as R2.adj improves and R2.adj ## remains below R2.adj < R2.all R2.previous <- R2.0 repeat { if (trace) { cat("Step: R2.adj=", R2.previous, "\n") cat(pasteCall(formula(object)), "\n") } adds <- add.scope(object, scope) ## Nothing to add and we're done: break if (length(adds) == 0) break R2.adds <- numeric(length(adds)) adds <- paste("+", adds) names(R2.adds) <- adds ## Loop over add scope for (trm in seq_along(R2.adds)) { fla <- paste(". ~ .", names(R2.adds[trm])) R2.tmp <- RsquareAdj(update(object, fla), permutations = R2permutations, ...)$adj.r.squared if (!length(R2.tmp)) R2.tmp <- 0 R2.adds[trm] <- R2.tmp } best <- which.max(R2.adds) if (trace) { out <- sort(c("<All variables>" = R2.all, "<none>" = R2.previous, R2.adds), decreasing = TRUE) out <- as.matrix(out) colnames(out) <- "R2.adjusted" print(out) cat("\n") } ## See if the best should be kept ## First criterion: R2.adj improves and is still lower or ## equal than for the full model of the scope if (R2.adds[best] > R2.previous && (!R2scope || R2scope && R2.adds[best] <= R2.all)) { ## Second criterion: added variable is significant tst <- add1(object, scope = adds[best], test="permu", permutations = permutations, alpha = Pin, trace = FALSE, ...) if (trace) { print(tst[-1,]) cat("\n") } if (tst[,"Pr(>F)"][2] <= Pin) { fla <- paste("~ .", names(R2.adds[best])) object <- update(object, fla) } else break } else { break } R2.previous <- RsquareAdj(object, permutations = R2permutations, ...)$adj.r.squared anotab <- rbind(anotab, cbind("R2.adj" = R2.previous, tst[2,])) } if (NROW(anotab)) { if (R2scope) anotab <- rbind(anotab, "<All variables>" = c(R2.all, rep(NA, 4))) class(anotab) <- c("anova", class(anotab)) object$anova <- anotab } object }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiR2step.R
`ordiTerminfo` <- function(d, data) { Terms <- delete.response(d$terms.expand) if (length(attr(Terms, "term.labels")) == 0) mf <- data.frame(NULL) else mf <- d$modelframe xlev <- .getXlevels(Terms, mf) ordered <- sapply(mf, is.ordered) assign <- attr(d$Y, "assign") list(terms = Terms, assign = assign, xlev = xlev, ordered = ordered) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiTerminfo.R
#' Extract internal working matrices from constrained ordination object #' #' Function extract internal working matrices from the constrained #' ordination object (class \code{"cca"}) in \pkg{vegan}. The function #' returns only one model matrix type, but there is no overlap between #' elements of typical request. #' #' @param x ordination object #' @param model model to be extracted #' `ordiYbar` <- function(x, model = c("CCA", "CA", "pCCA", "partial", "initial")) { model <- match.arg(model) isDB <- inherits(x, "dbrda") if (!is.null(x$Ybar)) Ybar <- x$Ybar else return(vegan24Xbar(x, model)) if (model == "initial") return(Ybar) ## return NULL for missing elements if (model != "partial") if(is.null(x[[model]])) return(NULL) ## edit Ybar -- not yet dbrda switch(model, "pCCA" = { Ybar <- qr.fitted(x$pCCA$QR, Ybar) if (isDB) Ybar <- qr.fitted(x$pCCA$QR, t(Ybar)) }, "partial" = { if (!is.null(x$pCCA)) { Ybar <- qr.resid(x$pCCA$QR, Ybar) if (isDB) Ybar <- qr.resid(x$pCCA$QR, t(Ybar)) } }, "CCA" = { if (!is.null(x$pCCA)) { Ybar <- qr.resid(x$pCCA$QR, Ybar) if (isDB) Ybar <- qr.resid(x$pCCA$QR, t(Ybar)) } Ybar <- qr.fitted(x$CCA$QR, Ybar) if (isDB) Ybar <- qr.fitted(x$CCA$QR, t(Ybar)) }, "CA" = { if (!is.null(x$CCA)) { Ybar <- qr.resid(x$CCA$QR, Ybar) if (isDB) Ybar <- qr.resid(x$CCA$QR, t(Ybar)) } else if (!is.null(x$pCCA)) { Ybar <- qr.resid(x$pCCA$QR, Ybar) if (isDB) Ybar <- qr.resid(x$pCCA$QR, t(Ybar)) } }) Ybar } #' Extract internal working matrices of cca objects for vegan 2.4 `vegan24Xbar` <- function(x, model = c("CCA", "CA", "pCCA", "partial", "initial")) { model <- match.arg(model) ## return NULL for missing elements if (model %in% c("CCA", "CA", "pCCA")) if(is.null(x[[model]])) return(NULL) Ybar <- NULL ## initial working data is not saved and must be reconstructed in ## partial models, but this cannot be done in all cases. if (model == "initial") { if (inherits(x, "dbrda")) { ## NULL in partial models if (is.null(x$pCCA)) { Ybar <- x$CCA$Xbar if (is.null(Ybar)) Ybar <- x$CA$Xbar } } else { ## this will ignore imaginary components in capscale if (is.null(x$CCA)) Ybar <- x$CA$Xbar else Ybar <- x$CCA$Xbar if (!is.null(x$pCCA)) Ybar <- Ybar + x$pCCA$Fit } ## vegan 2.5 compatibility: returns Ybar divided with d.o.f. if (x$inertia == "variance") Ybar <- Ybar/sqrt(nobs(x)-1) return(Ybar) } ## several components are already stored in the result object and ## we just fetch those (only CCA needs work) switch(model, "pCCA" = Ybar <- x$pCCA$Fit, "partial" = { Ybar <- x$CCA$Xbar if (is.null(Ybar)) Ybar <- x$CA$Xbar }, "CCA" = { Ybar <- qr.fitted(x$CCA$QR, x$CCA$Xbar) if (inherits(x, "dbrda")) Ybar <- qr.fitted(x$CCA$QR, t(Ybar)) }, "CA" = Ybar <- x$CA$Xbar ) ## vegan 2.5 divides Ybar with sqrt(n-1) in rda for variance if (x$inertia == "variance") Ybar <- Ybar/sqrt(nobs(x)-1) Ybar }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiYbar.R
#' Permutation test for the area of convex hull or ellipse in ordination #' #' Finds if the area covered by a convex hull or fitted ellipse is #' smaller than expected under null hypothesis using permutation test. #' #' @param ord 2-d ordination #' @param factor defining groups #' @param are of convex hull of or an ellipse #' @param permutations: number, permutation matrix or a #' \code{\link[permute]{how}} definition. #' @param parallel parallel processing #' @param \dots other parameters passed to area functions #' #' @author Jari Oksanen `ordiareatest` <- function(ord, groups, area = c("hull", "ellipse"), kind = "sd", permutations = 999, parallel = getOption("mc.cores"), ...) { EPS <- sqrt(.Machine$double.eps) ## Function to find area area <- match.arg(area) areafun <- if (area == "hull") ordihull else ordiellipse areafun <- match.fun(areafun) ## Observed statistics obs <- summary(areafun(ord, groups, draw = "none", kind = kind))["Area",] ## permutations pfun <- function(take, ...) summary(areafun(ord, groups[take], draw = "none", kind = kind))["Area",] perm <- getPermuteMatrix(permutations, length(groups)) nperm <- nrow(perm) if (is.null(parallel)) parallel <- 1 hasClus <- inherits(parallel, "cluster") if (hasClus || parallel > 1) { if(.Platform$OS.type == "unix" && !hasClus) { areas <- do.call(cbind, mclapply(1:nperm, function(i, ...) pfun(perm[i,],...), mc.cores = parallel)) } else { if (!hasClus) { parallel <- makeCluster(parallel) } areas <- parApply(parallel, perm, MARGIN=1, pfun) if (!hasClus) stopCluster(parallel) } } else { areas <- sapply(1:nperm, function(i, ...) pfun(perm[i,], ...)) } signif <- (rowSums(areas <= obs + EPS) + 1)/(nperm + 1) out <- list("areas" = obs, "pvalues" = signif, "permutations" = areas, nperm = nperm, control = attr(perm, "control"), "kind" = area) class(out) <- "ordiareatest" out } ### print method `print.ordiareatest` <- function(x, ...) { qu <- apply(x$permutations, 1, quantile, probs=c(0.05, 0.5)) m <- cbind("Area" = x$areas, t(qu), "Pr(<sim)" = x$pvalues) cat("\n") cat(sprintf("Permutation test for the size of ordination %s\nalternative hypothesis: observed area is smaller than random %s\n\n", x$kind, x$kind)) cat(howHead(x$control), "\n") printCoefmat(m, tst.ind=1:3) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiareatest.R
`ordiarrows` <- function (ord, groups, levels, replicates, order.by, display = "sites", col = 1, show.groups, startmark, label = FALSE, length = 0.1, ...) { pts <- scores(ord, display = display, ...) npoints <- nrow(pts) if (missing(groups)) groups <- gl(levels, replicates, npoints) if (!missing(order.by)) { if (length(order.by) != nrow(pts)) stop(gettextf("the length of order.by (%d) does not match the number of points (%d)", length(order.by), nrow(pts))) ord <- order(order.by) pts <- pts[ord,] groups <- groups[ord] } if (!missing(show.groups)) { take <- groups %in% show.groups pts <- pts[take, , drop = FALSE] groups <- groups[take] } out <- seq(along = groups) inds <- names(table(groups)) if (is.factor(col)) col <- as.numeric(col) col <- rep(col, length=length(inds)) names(col) <- inds starts <- names <- NULL for (is in inds) { gr <- out[groups == is] if (length(gr) > 1) { X <- pts[gr, , drop = FALSE] ## zero length arrows will give warning and miss arrowhead nonzeroarrow <- rowSums(diff(X)^2) > 100*sqrt(.Machine$double.eps) if (!all(nonzeroarrow)) X <- X[c(TRUE, nonzeroarrow),, drop=FALSE] if (nrow(X) < 2) next X0 <- X[-nrow(X), , drop = FALSE] X1 <- X[-1, , drop = FALSE] nseg <- nrow(X0) if (!missing(startmark)) points(X0[1,1], X0[1,2], pch=startmark, col = col[is], ...) if (label) { starts <- rbind(starts, X0[1,]) names <- c(names, is) } if (nseg > 1) ordiArgAbsorber(X0[-nseg,1], X0[-nseg,2], X1[-nseg,1], X1[-nseg,2], col = col[is], FUN = segments, ...) ordiArgAbsorber(X0[nseg, 1], X0[nseg, 2], X1[nseg, 1], X1[nseg, 2], col = col[is], length = length, FUN = arrows, ...) } } if (label) ordiArgAbsorber(starts, labels = names, border = col, col = par("fg"), FUN = ordilabel, ...) invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiarrows.R
### draws crossed error bars for classes in ordination. These are ### oblique to axis because so are th clouds of the points and their ### standard errors and confidence regions. The bars are principal ### axes of corresponding ellipse (as drawn in ordiellipse), and found ### as principal components of the associate covariance matrix. The ### function is modelled after ordiellipse. `ordibar` <- function (ord, groups, display = "sites", kind = c("sd", "se"), conf, w = weights(ord, display), col = 1, show.groups, label = FALSE, lwd = NULL, length = 0, ...) { weights.default <- function(object, ...) NULL kind <- match.arg(kind) pts <- scores(ord, display = display, ...) ## ordibar only works with 2D data (2 columns) pts <- as.matrix(pts) if (ncol(pts) > 2) pts <- pts[ , 1:2, drop = FALSE] if (ncol(pts) < 2) stop("needs two dimensions") w <- eval(w) if (length(w) == 1) w <- rep(1, nrow(pts)) if (is.null(w)) w <- rep(1, nrow(pts)) if (!missing(show.groups)) { take <- groups %in% show.groups pts <- pts[take, , drop = FALSE] groups <- groups[take] w <- w[take] } out <- seq(along = groups) inds <- names(table(groups)) if (label) { cntrs <- matrix(NA, nrow=length(inds), ncol=2) rownames(cntrs) <- inds } col <- rep(col, length = length(inds)) names(col) <- inds res <- list() ## Remove NA scores kk <- complete.cases(pts) & !is.na(groups) for (is in inds) { gr <- out[groups == is & kk] if (length(gr)) { X <- pts[gr, , drop = FALSE] W <- w[gr] mat <- cov.wt(X, W) if (mat$n.obs == 1) mat$cov[] <- 0 if (kind == "se") mat$cov <- mat$cov * sum(mat$wt^2) if (missing(conf)) t <- 1 else t <- sqrt(qchisq(conf, 2)) if (mat$n.obs > 1) { eig <- eigen(mat$cov, symmetric = TRUE) v <- sweep(eig$vectors, 2, sqrt(eig$values), "*") * t cnt <- mat$center ordiArgAbsorber(v[1,] + cnt[1], v[2,] + cnt[2], -v[1,] + cnt[1], -v[2,] + cnt[2], col = col[is], lwd = lwd, length = length/2, angle = 90, code = 3, FUN = arrows, ...) } if (label) { cntrs[is,] <- mat$center } mat$scale <- t res[[is]] <- mat } } if (label) { ordiArgAbsorber(cntrs, col = par("fg"), border = col, FUN = ordilabel, ...) } class(res) <- "ordibar" invisible(res) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordibar.R
`ordicloud` <- function(x, data = NULL, formula, display = "sites", choices=1:3, panel = "panel.ordi3d", prepanel = "prepanel.ordi3d", ...) { localCloud <- function(..., shrink, origin, scaling) cloud(...) x <- as.data.frame(scores(x, display = display, choices = choices, ...)) if (!is.null(data)) x <- cbind(x, data) if (missing(formula)) { v <- colnames(x) formula <- as.formula(paste(v[2], "~", v[1], "*", v[3])) } localCloud(formula, data = x, panel = panel, prepanel = prepanel, ...) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordicloud.R
`ordicluster` <- function (ord, cluster, prune = 0, display = "sites", w = weights(ord, display), col = 1, draw = c("segments", "none"), ...) { weights.default <- function(object, ...) NULL w <- eval(w) mrg <- cluster$merge ord <- scores(ord, display = display, ...) if (nrow(mrg) != nrow(ord) - 1) stop("dimensions do not match in 'ord' and 'cluster'") if (length(w) == 1) w <- rep(w, nrow(ord)) n <- if (is.null(w)) rep(1, nrow(ord)) else w noden <- numeric(nrow(mrg) - prune) go <- matrix(0, nrow(mrg) - prune, 2) ## recycle colours for points and prepare to get node colours col <- rep(col, length = nrow(ord)) col <- col2rgb(col)/255 nodecol <- matrix(NA, nrow(mrg) - prune, 3) seg.coords <- matrix(NA, nrow = nrow(mrg) - prune, ncol = 4) for (i in seq_len(nrow(mrg) - prune)) { a <- mrg[i,1] b <- mrg[i,2] one <- if (a < 0) ord[-a,] else go[a,] two <- if (b < 0) ord[-b,] else go[b,] n1 <- if (a < 0) n[-a] else noden[a] n2 <- if (b < 0) n[-b] else noden[b] xm <- weighted.mean(c(one[1],two[1]), w = c(n1,n2)) ym <- weighted.mean(c(one[2],two[2]), w = c(n1,n2)) go[i,] <- c(xm,ym) noden[i] <- n1 + n2 colone <- if (a < 0) col[,-a] else nodecol[a,] coltwo <- if (b < 0) col[,-b] else nodecol[b,] nodecol[i,] <- (n1 * colone + n2 * coltwo)/noden[i] seg.coords[i, ] <- c(one[1], one[2], two[1], two[2]) } colnames(seg.coords) <- c("x1","y1","x2","y2") ## are we plotting? draw <- match.arg(draw) if (isTRUE(all.equal(draw, "segments"))) { ordiArgAbsorber(seg.coords[,1L], seg.coords[,2L], seg.coords[,3L], seg.coords[,4L], col = rgb(nodecol), FUN = segments, ...) } colnames(go) <- c("x","y") seg.coords <- cbind(as.data.frame(seg.coords), col = rgb(nodecol)) out <- structure(list(scores = cbind(go, "w" = noden), segments = seg.coords), class = "ordicluster") invisible(out) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordicluster.R
`ordiellipse` <- function (ord, groups, display = "sites", kind = c("sd", "se", "ehull"), conf, draw = c("lines", "polygon", "none"), w = weights(ord, display), col = NULL, alpha = 127, show.groups, label = FALSE, border = NULL, lty = NULL, lwd = NULL, ...) { weights.default <- function(object, ...) NULL kind <- match.arg(kind) draw <- match.arg(draw) pts <- scores(ord, display = display, ...) ## ordiellipse only works with 2D data (2 columns) pts <- as.matrix(pts) if (ncol(pts) > 2) pts <- pts[ , 1:2, drop = FALSE] if (ncol(pts) < 2) stop("needs two dimensions") w <- eval(w) if (length(w) == 1) w <- rep(1, nrow(pts)) if (is.null(w)) w <- rep(1, nrow(pts)) ## make semitransparent fill; alpha should be integer in 0..255, ## but users may have given that as real in 0..1 if (alpha < 1) alpha <- round(alpha * 255) if (draw == "polygon" && !is.null(col)) col <- rgb(t(col2rgb(col)), alpha = alpha, maxColorValue = 255) if (!missing(show.groups)) { take <- groups %in% show.groups pts <- pts[take, , drop = FALSE] groups <- groups[take] w <- w[take] } out <- seq(along = groups) inds <- names(table(groups)) ## fill in graphical vectors with default values if unspecified ## and recycles shorter vectors col.new <- border.new <- lty.new <- lwd.new <- NULL for(arg in c("col","border","lty","lwd")){ tmp <- mget(arg,ifnotfound=list(NULL))[[1]] if(is.null(tmp)) tmp <- ifelse(suppressWarnings(is.null(par(arg))), par("fg"), par(arg)) if(length(inds) != length(tmp)) {tmp <- rep_len(tmp, length(inds))} assign(paste(arg,".new", sep=""), tmp) } ## default colour for "polygon" fill is "transparent", for lines ## is par("fg") if(is.null(col) && draw=="polygon") col.new <- rep_len("transparent", length(inds)) else if(is.null(col) && draw=="lines") col.new <- rep_len(par("fg"), length(inds)) res <- list() if (label) { cntrs <- matrix(NA, nrow=length(inds), ncol=2) rownames(cntrs) <- inds } ## Remove NA scores kk <- complete.cases(pts) & !is.na(groups) for (is in inds) { gr <- out[groups == is & kk] if (length(gr)) { X <- pts[gr, , drop = FALSE] W <- w[gr] if (kind == "ehull") { tmp <- ellipsoidhull(X) mat <- list(cov = tmp$cov, center = tmp$loc, n.obs = nrow(X)) } else mat <- cov.wt(X, W) if (mat$n.obs == 1) mat$cov[] <- 0 if (kind == "se") mat$cov <- mat$cov * sum(mat$wt^2) if (kind == "ehull") t <- if (is.nan(tmp$d2)) 0 else sqrt(tmp$d2) else { if (missing(conf)) t <- 1 else t <- sqrt(qchisq(conf, 2)) } if (mat$n.obs > 1) xy <- veganCovEllipse(mat$cov, mat$center, t) else xy <- X if (draw == "lines") ordiArgAbsorber(xy, FUN = lines, col = if (is.null(col)) par("fg") else col.new[match(is, inds)], lty=lty.new[match(is,inds)], lwd=lwd.new[match(is,inds)], ...) else if (draw == "polygon") ordiArgAbsorber(xy[, 1], xy[, 2], col = col.new[match(is, inds)], border=border.new[match(is,inds)], lty = lty.new[match(is,inds)], lwd = lwd.new[match(is,inds)], FUN = polygon, ...) if (label && draw != "none") { cntrs[is,] <- mat$center } mat$scale <- t res[[is]] <- mat } } if (label && draw != "none") { if (draw == "lines") ordiArgAbsorber(cntrs[,1], cntrs[,2], labels = rownames(cntrs), col = col.new, FUN = text, ...) else ordiArgAbsorber(cntrs, col = NULL, FUN = ordilabel, ...) } class(res) <- "ordiellipse" invisible(res) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiellipse.R
"ordigrid" <- function (ord, levels, replicates, display = "sites", lty=c(1,1), col=c(1,1), lwd = c(1,1), ...) { pts <- scores(ord, display = display, ...) npoints <- nrow(pts) gr <- gl(levels, replicates, npoints) ordisegments(pts, groups = gr, lty = lty[1], col = col[1], lwd = lwd[1], ...) gr <- gl(replicates, 1, npoints) ordisegments(pts, groups = gr, lty = lty[2], col = col[2], lwd = lwd[2], ...) invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordigrid.R
`ordihull` <- function (ord, groups, display = "sites", draw = c("lines", "polygon", "none"), col = NULL, alpha = 127, show.groups, label = FALSE, border = NULL, lty = NULL, lwd = NULL, ...) { draw <- match.arg(draw) ## Internal function to find the polygon centre polycentre <- function(x) { n <- nrow(x) if (n < 4) return(colMeans(x[-n, , drop = FALSE])) xy <- x[-n, 1] * x[-1, 2] - x[-1, 1] * x[-n, 2] A <- sum(xy)/2 xc <- sum((x[-n, 1] + x[-1, 1]) * xy)/A/6 yc <- sum((x[-n, 2] + x[-1, 2]) * xy)/A/6 c(xc, yc) } ## Make semitransparent fill colour; alpha should be integer ## 0..255, but we also handle real values < 1 if (alpha < 1) alpha <- round(alpha * 255) if (draw == "polygon" && !is.null(col)) col <- rgb(t(col2rgb(col)), alpha = alpha, maxColorValue = 255) pts <- scores(ord, display = display, ...) if (!missing(show.groups)) { take <- groups %in% show.groups pts <- pts[take, , drop = FALSE] groups <- groups[take] } out <- seq(along = groups) inds <- names(table(groups)) ## fill in graphical vectors with default values if unspecified ## and recycles shorter vectors col.new <- border.new <- lty.new <- lwd.new <- NULL for(arg in c("col","border","lty","lwd")){ tmp <- mget(arg,ifnotfound=list(NULL))[[1]] if(is.null(tmp)) tmp <- ifelse(suppressWarnings(is.null(par(arg))), par("fg"), par(arg)) if(length(inds) != length(tmp)) tmp <- rep_len(tmp, length(inds)) assign(paste(arg,".new", sep=""), tmp) } ## default colour for "polygon" fill is "transparent", for lines ## is par("fg") if(is.null(col) && draw=="polygon") col.new <- rep_len("transparent", length(inds)) else if(is.null(col) && draw=="lines") col.new <- rep_len(par("fg"), length(inds)) res <- list() if (label) { cntrs <- matrix(NA, nrow=length(inds), ncol=2) rownames(cntrs) <- inds } ## Remove NA scores kk <- complete.cases(pts) & !is.na(groups) for (is in inds) { gr <- out[groups == is & kk] if (length(gr)) { X <- pts[gr,, drop = FALSE] hpts <- chull(X) hpts <- c(hpts, hpts[1]) if (draw == "lines") ordiArgAbsorber(X[hpts, ], FUN = lines, col = if (is.null(col)) par("fg") else col.new[match(is, inds)], lty = lty.new[match(is,inds)], lwd = lwd.new[match(is,inds)], ...) else if (draw == "polygon") ordiArgAbsorber(X[hpts, ], border= border.new[match(is,inds)], FUN = polygon, col = col.new[match(is, inds)], lty = lty.new[match(is,inds)], lwd=lwd.new[match(is,inds)], ...) if (label && draw != "none") { cntrs[is,] <- polycentre(X[hpts,]) } res[[is]] <- X[hpts,] } } if (label && draw != "none") { if (draw == "lines") ordiArgAbsorber(cntrs[, 1], cntrs[, 2], labels = rownames(cntrs), col = col.new[match(is, inds)], FUN = text, ...) else ordiArgAbsorber(cntrs, labels = rownames(cntrs), col = NULL, FUN = ordilabel, ...) } class(res) <- "ordihull" invisible(res) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordihull.R
`ordilabel` <- function(x, display, labels, choices = c(1,2), priority, select, cex = 0.8, fill = "white", border = NULL, col = NULL, xpd = TRUE, ...) { if (missing(display)) display <- "sites" x <- scores(x, choices = choices, display = display, ...) if (missing(labels)) labels <- rownames(x) if (!missing(select)) { x <- .checkSelect(select, x) labels <- .checkSelect(select, labels) } if (!missing(priority)) { if (!missing(select)) priority <- priority[select] ord <- order(priority) x <- x[ord, ] labels <- labels[ord] } else { ord <- seq_along(labels) } em <- strwidth("m", cex = cex, ...) ex <- strheight("x", cex = cex, ...) w <- (strwidth(labels, cex=cex,...) + em/1.5)/2 h <- (strheight(labels, cex = cex, ...) + ex/1.5)/2 if (is.null(col)) if (!is.null(border)) col <- border else col <- par("fg") col <- rep(col, length=nrow(x))[ord] if(!is.null(border)) border <- rep(border, length=nrow(x))[ord] fill <- rep(fill, length=nrow(x))[ord] for (i in 1:nrow(x)) { ordiArgAbsorber(x[i,1] + c(-1,1,1,-1)*w[i], x[i,2] + c(-1,-1,1,1)*h[i], col = fill[i], border = border[i], xpd = xpd, FUN = polygon, ...) ordiArgAbsorber(x[i,1], x[i,2], labels = labels[i], cex = cex, col = col[i], xpd = xpd, FUN = text, ...) } invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordilabel.R
`ordilattice.getEnvfit` <- function(formula, object, envfit, choices = 1:3, ...) { if (!missing(envfit) && !is.null(envfit)) object <- envfit bp <- scores(object, display = "bp", choices = choices, ...) cn <- scores(object, display = "cn", choices = choices, ...) bp <- bp[!(rownames(bp) %in% rownames(cn)),, drop=FALSE] left <- as.character(formula[[2]]) right <- formula[[3]] if (length(right) == 3) right <- right[[2]] right <- as.character(right) if (all(c(left,right) %in% colnames(bp))) bp <- bp[, c(left,right), drop=FALSE] else bp <- NULL if (!is.null(bp) && nrow(bp) == 0) bp <- NULL if (!is.null(ncol(cn)) && all(c(left,right) %in% colnames(cn))) cn <- cn[, c(left,right), drop=FALSE] else cn <- NULL list(arrows = bp, centres = cn) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordilattice.getEnvfit.R
## Ordimedian finds the spatial medians for groups. Spatial medians ## are L1 norms or statistics that minimize sum of distances of points ## from the statistic and 1d they are the medians. The current ## algorithm minimizes the L1 norm with optim and is pretty ## inefficient. Package ICSNP has a better algorithm (and we may steal ## it from them later). `ordimedian` <- function(ord, groups, display = "sites", label = FALSE, ...) { ## Sum of distances from the statistic medfun <- function(x, ord) sum(sqrt(rowSums(sweep(ord, 2, x)^2)), na.rm = TRUE) ## derivative of medfun (if NULL, optim will use numerical ## differentiation) dmedfun <- function(x, ord) { up <- -sweep(ord, 2, x) dn <- sqrt(rowSums(sweep(ord, 2, x)^2)) colSums(sweep(up, 1, dn, "/")) } #dmedfun <- NULL pts <- scores(ord, display = display, ...) inds <- names(table(groups)) medians <- matrix(NA, nrow = length(inds), ncol = ncol(pts)) rownames(medians) <- inds colnames(medians) <- colnames(pts) for (i in inds) { X <- pts[groups == i, , drop = FALSE] if (NROW(X) > 0) medians[i, ] <- optim(apply(X, 2, median, na.rm = TRUE), fn = medfun, gr = dmedfun, ord = X, method = "BFGS")$par if(label) ordiArgAbsorber(medians[i,1], medians[i,2], label = i, FUN = text, ...) } invisible(medians) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordimedian.R
`ordiplot` <- function (ord, choices = c(1, 2), type = "points", display, xlim, ylim, cex = 0.7, ...) { ## local functions to absorb non-par arguments of plot.default localPoints <- function(..., log, frame.plot, panel.first, panel.last, axes) points(...) localText <- function(..., log, frame.plot, panel.first, panel.last, axes) text(...) if (inherits(ord, "decorana") || inherits(ord, "cca")) { if (missing(display)) out <- plot(ord, choices = choices, type = type, xlim = xlim, ylim = ylim, cex = cex, ...) else out <- plot(ord, choices = choices, type = type, display = display, xlim = xlim, ylim = ylim, cex = cex, ...) } else { type <- match.arg(type, c("points", "text", "none")) ## Matching displays could be done better (see ## ordipointlabel), but this may not be yet broken, so... dplays <- c("sites", "species") if (missing(display)) display <- dplays else display <- match.arg(display, dplays, several.ok = TRUE) X <- Y <- NULL if ("sites" %in% display) X <- scores(ord, choices = choices, display = "sites") if ("species" %in% display) { op <- options(show.error.messages = FALSE) Y <- try(scores(ord, choices = choices, display = "species")) options(op) if (inherits(Y, "try-error")) { message("species scores not available") Y <- NULL } else if (!is.null(X) && NROW(X) == NROW(Y) && isTRUE(all.equal.numeric(X, Y, check.attributes = FALSE))) { Y <- NULL message("species scores not available") } } if (is.null(X) && is.null(Y)) stop("no scores found: nothing to plot") ## Use linestack and exit if there is only one dimension if (NCOL(X) == 1 && NCOL(Y) == 1) { pl <- linestack(X, ylim = range(c(X,Y), na.rm=TRUE), cex = cex, ...) if (!is.null(Y)) linestack(Y, side = "left", add = TRUE, cex = cex, ...) return(invisible(pl)) } tmp <- apply(rbind(X, Y), 2, range, na.rm=TRUE) if (missing(xlim)) xlim <- tmp[, 1] if (missing(ylim)) ylim <- tmp[, 2] plot(tmp, xlim = xlim, ylim = ylim, asp = 1, type = "n", ...) if (type == "points") { if (!is.null(X)) localPoints(X, pch = 1, col = 1, cex = cex, ...) if (!is.null(Y)) localPoints(Y, pch = "+", col = "red", cex = cex, ...) } if (type == "text") { if (!is.null(X)) localText(X, labels = rownames(X), col = 1, cex = cex, ...) if (!is.null(Y)) localText(Y, labels = rownames(Y), col = "red", cex = cex, ...) } out <- list(sites = X, species = Y) } class(out) <- "ordiplot" invisible(out) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiplot.R
### Modelled after maptools:::pointLabel. `ordipointlabel` <- function(x, display = c("sites", "species"), choices = c(1,2), col=c(1,2), pch=c("o","+"), font = c(1,1), cex=c(0.8, 0.8), add = FALSE, select, ...) { xy <- list() ## Some 'scores' accept only one 'display': a workaround for (nm in display) xy[[nm]] <- scores(x, display = nm, choices = choices, ...) ##xy <- scores(x, display = display, choices = choices, ...) ## remove `select`ed observations from scores as per text.cca ## only useful if we are displaying only one set of scores if(!missing(select)) { if(isTRUE(all.equal(length(display), 1L))) { xy[[1]] <- .checkSelect(select, xy[[1]]) } else { warning("'select' does not apply when plotting more than one set of scores--\n'select' was ignored") } } if (length(display) > 1) { col <- rep(col, sapply(xy, nrow)) pch <- rep(pch, sapply(xy, nrow)) font <- rep(font, sapply(xy, nrow)) cex <- rep(cex, sapply(xy, nrow)) tmp <- xy[[1]] for (i in 2:length(display)) tmp <- rbind(tmp, xy[[i]]) xy <- tmp } else { xy <- xy[[1]] if (length(col) < nrow(xy)) col <- col[1] if (length(pch) < nrow(xy)) pch <- pch[1] if (length(font) < nrow(xy)) font <- font[1] } if (!add) pl <- ordiplot(x, display = display, choices = choices, type="n", ...) labels <- rownames(xy) em <- strwidth("m", cex = min(cex), font = min(font)) ex <- strheight("x", cex = min(cex), font = min(font)) ltr <- em*ex w <- strwidth(labels, cex = cex, font = font) + em h <- strheight(labels, cex = cex, font = font) + ex box <- cbind(w, h) ## offset: 1 up, 2..4 sides, 5..8 corners makeoff <- function(pos, lab) { cbind(c(0,1,0,-1,0.9,0.9,-0.9,-0.9)[pos] * lab[,1]/2, c(1,0,-1,0,0.8,-0.8,-0.8,0.8)[pos] * lab[,2]/2) } ## amount of overlap overlap <- function(xy1, off1, xy2, off2) { pmax(0, pmin(xy1[,1] + off1[,1]/2, xy2[,1] + off2[,1]/2) -pmax(xy1[,1] - off1[,1]/2, xy2[,1] - off2[,1]/2)) * pmax(0, pmin(xy1[,2] + off1[,2]/2, xy2[,2] + off2[,2]/2) -pmax(xy1[,2] - off1[,2]/2, xy2[,2] - off2[,2]/2)) } ## indices of overlaps in lower triangular matrix n <- nrow(xy) j <- as.vector(as.dist(row(matrix(0, n, n)))) k <- as.vector(as.dist(col(matrix(0, n, n)))) ## Find labels that may overlap... maylap <- overlap(xy[j,], 2*box[j,], xy[k,], 2*box[k,]) > 0 ## ... and work only with those j <- j[maylap] k <- k[maylap] jk <- sort(unique(c(j,k))) ## SANN: no. of iterations & starting positions nit <- min(48 * length(jk), 10000) pos <- rep(1, n) ## Criterion: overlap + penalty for positions other than directly ## above and especially for corners fn <- function(pos) { off <- makeoff(pos, box) val <- sum(overlap(xy[j,]+off[j,], box[j,], xy[k,]+off[k,], box[k,])) val <- val/ltr + sum(pos>1)*0.1 + sum(pos>4)*0.1 } ## Move a label of one point gr <- function(pos) { take <- sample(jk, 1) pos[take] <- sample((1:8)[-pos[take]], 1) pos } ## Simulated annealing sol <- optim(par = pos, fn = fn, gr = gr, method="SANN", control=list(maxit=nit)) if (!add) ##points(xy, pch = pch, col = col, cex=cex, ...) ordiArgAbsorber(xy, pch = pch, col = col, cex = cex, FUN = points, ...) lab <- xy + makeoff(sol$par, box) ##text(lab, labels=labels, col = col, cex = cex, font = font, ...) ordiArgAbsorber(lab, labels=labels, col = col, cex = cex, font = font, FUN = text, ...) pl <- list(points = xy) pl$labels <- lab attr(pl$labels, "font") <- font args <- list(tcex = cex, tcol = col, pch = pch, pcol = col, pbg = NA, pcex = cex) pl$args <- args pl$par <- par(no.readonly = TRUE) pl$dim <- par("din") attr(pl, "optim") <- sol class(pl) <- c("ordipointlabel", "orditkplot", class(pl)) invisible(pl) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordipointlabel.R
`ordiresids` <- function(x, kind = c("residuals", "scale", "qqmath"), residuals = "working", type = c("p", "smooth", "g"), formula, ...) { kind <- match.arg(kind) if (!inherits(x, "cca") || is.null(x$CCA) || x$CCA$rank == 0) stop("function is only available for constrained ordination") residuals <- match.arg(residuals, c("working", "response", "standardized", "studentized")) fit <- switch(residuals, "working" =, "response" = fitted(x, type = residuals), "standardized" =, "studentized" = sweep(fitted(x, type="working"), 2, sigma(x), "/")) res <- switch(residuals, "standardized" = rstandard(x), "studentized" = rstudent(x), residuals(x, type = residuals)) colnam <- rep(colnames(fit), each=nrow(fit)) rownam <- rep(rownames(fit), ncol(fit)) df <- data.frame(Fitted = as.vector(fit), Residuals = as.vector(res)) if (!is.null(rownam)) df$Sites <- rownam if (!is.null(colnam)) df$Species <- colnam if (kind == "residuals") { if (missing(formula)) formula <- as.formula(Residuals ~ Fitted) pl <- xyplot(formula, data = df, type = type, ...) } if (kind == "scale") { if (missing(formula)) formula <- as.formula(sqrt(abs(Residuals)) ~ Fitted) pl <- xyplot(formula, data = df, type = type, ...) } if (kind == "qqmath") { if (missing(formula)) formula <- as.formula(~ Residuals) pl <- qqmath(formula, data = df, type = type, ...) } pl }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordiresids.R
`ordisegments` <- function (ord, groups, levels, replicates, order.by, display = "sites", col = 1, show.groups, label = FALSE, ...) { pts <- scores(ord, display = display, ...) npoints <- nrow(pts) if (missing(groups)) groups <- gl(levels, replicates, npoints) if (!missing(order.by)) { if (length(order.by) != nrow(pts)) stop(gettextf("the length of order.by (%d) does not match the number of points (%d)", length(order.by), nrow(pts))) ord <- order(order.by) pts <- pts[ord,] groups <- groups[ord] } if (!missing(show.groups)) { take <- groups %in% show.groups pts <- pts[take, , drop = FALSE] groups <- groups[take] } out <- seq(along = groups) inds <- names(table(groups)) if (is.factor(col)) col <- as.numeric(col) col <- rep(col, length=length(inds)) names(col) <- inds ends <- names <- NULL for (is in inds) { gr <- out[groups == is] if (length(gr) > 1) { X <- pts[gr, , drop = FALSE] X0 <- X[-nrow(X), , drop = FALSE] X1 <- X[-1, , drop = FALSE] ordiArgAbsorber(X0[, 1], X0[, 2], X1[, 1], X1[, 2], col = col[is], FUN = segments, ...) if (label) { ends <- rbind(ends, X[c(1, nrow(X)), ]) names <- c(names, is, is) } } } if (label) ordiArgAbsorber(ends, labels = names, border = col, col = par("fg"), FUN = ordilabel, ...) invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordisegments.R
`ordispider` <- function (ord, groups, display = "sites", w = weights(ord, display), spiders = c("centroid", "median"), show.groups, label = FALSE, col = NULL, lty = NULL, lwd = NULL, ...) { weights.default <- function(object, ...) NULL spiders <- match.arg(spiders) if (inherits(ord, "cca") && missing(groups)) { lc <- scores(ord, display = "lc", ...) wa <- scores(ord, display = "wa", ...) if (is.null(col)) col <- par("fg") ordiArgAbsorber(lc[, 1], lc[, 2], wa[, 1], wa[, 2], FUN = segments, col = col, lty = lty, lwd = lwd, ...) class(lc) <- "ordispider" return(invisible(lc)) } pts <- scores(ord, display = display, ...) ## spids stores pointwise centroids to be returned invisibly ## (transposed here so that filling is easier, but back-transposed ## when returned). spids <- t(array(NA, dim=dim(pts), dimnames = dimnames(pts))) ## ordihull: draw lines from centre to the points in the hull if (inherits(ord, "ordihull")) groups <- attr(pts, "hulls") w <- eval(w) if (length(w) == 1) w <- rep(1, nrow(pts)) if (is.null(w)) w <- rep(1, nrow(pts)) if (!missing(show.groups)) { take <- groups %in% show.groups pts <- pts[take, , drop = FALSE] groups <- groups[take] w <- w[take] } if (spiders == "median" && sd(w) > sqrt(.Machine$double.eps)) warning("weights are ignored with 'median' spiders") out <- seq(along = groups) inds <- names(table(groups)) if (label) cntrs <- names <- NULL ## fill in graphical vectors with default values if unspecified ## and recycles shorter vectors for(arg in c("col","lty","lwd")) { tmp <- mget(arg,ifnotfound=list(NULL))[[1]] if(is.null(tmp)) tmp <- ifelse(suppressWarnings(is.null(par(arg))), par("fg"), par(arg)) if(length(inds) != length(tmp)) tmp <- rep_len(tmp, length(inds)) assign(arg, tmp) } ## 'kk' removes NA scores and NA groups kk <- complete.cases(pts) & !is.na(groups) for (is in inds) { gr <- out[groups == is & kk] if (length(gr)) { X <- pts[gr, , drop = FALSE] W <- w[gr] if (length(gr) > 1) { ave <- switch(spiders, "centroid" = apply(X, 2, weighted.mean, w = W), "median" = ordimedian(X, rep(1, nrow(X)))) ordiArgAbsorber(ave[1], ave[2], X[, 1], X[, 2], FUN = segments, col[match(is, inds)], lty = lty[match(is,inds)], lwd = lwd[match(is,inds)],...) } else { ave <- X } spids[,gr] <- ave if (label) { cntrs <- rbind(cntrs, ave) names <- c(names, is) } } } if (label) ordiArgAbsorber(cntrs, label = names, FUN = ordilabel, ...) spids <- t(spids) class(spids) <- "ordispider" invisible(spids) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordispider.R
`ordisplom` <- function(x, data=NULL, formula = NULL, display = "sites", choices = 1:3, panel = "panel.ordi", type = "p", ...) { localSplom <- function(..., shrink, origin, scaling) splom(...) x <- as.data.frame(scores(x, display = display, choices = choices, ...)) if (is.null(data)) data <- x else if (is.null(formula)) x <- cbind(x, data) ## type = "biplot" is not (yet?) implemented env <- list(arrows = NULL, centres = NULL) if (is.null(formula)) pl <- localSplom(x, panel = panel, type = type, biplot = env, ...) else { formula <- as.formula(gsub("\\.", "x", deparse(formula))) pl <- localSplom(x = formula, data = data, panel = panel, type = type, biplot = env, ...) } pl }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordisplom.R
`ordistep` <- function(object, scope, direction =c("both", "backward", "forward"), Pin = 0.05, Pout = 0.1, permutations = how(nperm = 199), steps=50, trace = TRUE, ...) { if (!inherits(object, "cca")) stop("function can be only used with 'cca' and related objects") if (is.null(object$terms)) stop("ordination model must be fitted using formula") ## handling 'direction' and 'scope' directly copied from ## stats::step() md <- missing(direction) direction <- match.arg(direction) backward <- direction == "both" | direction == "backward" forward <- direction == "both" | direction == "forward" ffac <- attr(terms(object), "factors") if (missing(scope)) { fdrop <- numeric(0) fadd <- ffac if (md) forward <- FALSE } else { if (is.list(scope) && (!is.null(scope$lower) || !is.null(scope$upper))) { fdrop <- if (!is.null(fdrop <- scope$lower)) attr(terms(update.formula(object, fdrop)), "factors") else numeric(0) fadd <- if (!is.null(fadd <- scope$upper)) attr(terms(update.formula(object, fadd)), "factors") } else { fadd <- if (!is.null(fadd <- scope)) attr(terms(update.formula(object, scope)), "factors") if (forward) fdrop <- attr(terms(object), "factor") else fdrop <- numeric(0L) } } scope <- factor.scope(ffac, list(add = fadd, drop = fdrop)) ## 'anotab' collects the changes into 'anova' object in the output anotab <- NULL if (trace) { cat("\n") cat(pasteCall(formula(object), prefix = "Start:")) } for (i in 1:steps){ change <- NULL ## Consider dropping if (backward && length(scope$drop)) { aod <- drop1(object, scope = scope$drop, test="perm", permutations = permutations, alpha = Pout, trace = trace, ...) aod <- aod[-1,] o <- order(-aod[,4], aod[,2]) aod <- aod[o,] rownames(aod) <- paste("-", rownames(aod), sep = " ") if (trace) { cat("\n") print(aod) } if (is.na(aod[1,4]) || aod[1,4] > Pout) { anotab <- rbind(anotab, aod[1,]) change <- rownames(aod)[1] object <- eval.parent(update(object, paste("~ .", change))) scope <- factor.scope(attr(terms(object), "factors"), list(add = fadd, drop = fdrop)) if (trace) { cat("\n") cat(pasteCall(formula(object), prefix = "Step:")) } } } ## Consider adding if (forward && length(scope$add)) { aod <- add1(object, scope = scope$add, test = "perm", permutations = permutations, alpha = Pin, trace = trace, ...) aod <- aod[-1,] o <- order(aod[,4], aod[,2]) aod <- aod[o,] rownames(aod) <- paste("+", rownames(aod), sep = " ") if (trace) { cat("\n") print(aod) } if (!is.na(aod[1,4]) && aod[1,4] <= Pin) { anotab <- rbind(anotab, aod[1,]) change <- rownames(aod)[1] object <- eval.parent(update(object, paste( "~ .",change))) scope <- factor.scope(attr(terms(object), "factors"), list(add = fadd, drop = fdrop)) if (trace) { cat("\n") cat(pasteCall(formula(object), prefix="Step:")) } } } ## No drop, no add: done if (is.null(change)) break } if (trace) cat("\n") object$anova <- anotab object }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordistep.R
`ordisurf` <- function(...) UseMethod("ordisurf") `ordisurf.formula` <- function(formula, data, ...) { if (missing(data)) data <- parent.frame() x <- formula[[2]] x <- eval.parent(x) formula[[2]] <- NULL y <- drop(as.matrix(model.frame(formula, data, na.action = na.pass))) if (NCOL(y) > 1) stop(gettextf("only one fitted variable allowed in the formula")) ordisurf(x, y, ...) } `ordisurf.default` <- function (x, y, choices = c(1, 2), knots = 10, family = "gaussian", col = "red", isotropic = TRUE, thinplate = TRUE, bs = "tp", fx = FALSE, add = FALSE, display = "sites", w = weights(x, display), main, nlevels = 10, levels, npoints = 31, labcex = 0.6, bubble = FALSE, cex = 1, select = TRUE, method = "REML", gamma = 1, plot = TRUE, lwd.cl = par("lwd"), ...) { weights.default <- function(object, ...) NULL if(!missing(thinplate)) { warning("use of 'thinplate' is deprecated and will soon be removed;\nuse 'isotropic' instead") isotropic <- thinplate } ## GRID no user-definable - why 31? GRID <- npoints w <- eval(w) if (!is.null(w) && length(w) == 1) w <- NULL X <- scores(x, choices = choices, display = display, ...) ## The original name of 'y' may be lost in handling NA: save for ## plots yname <- deparse(substitute(y)) kk <- complete.cases(X) & !is.na(y) if (!all(kk)) { X <- X[kk, , drop = FALSE] y <- y[kk] w <- w[kk] } x1 <- X[, 1] x2 <- X[, 2] ## handle fx - allow vector of length up to two if(!(missfx <- missing(fx)) && missing(knots)) warning("requested fixed d.f. splines but without specifying 'knots':\nswitching to 'fx = FALSE'") if (length(fx) > 2L) warning("length of 'fx' supplied exceeds '2': using the first two") ## expand fx robustly, no matter what length supplied fx <- rep(fx, length.out = 2) ## can't have `fx = TRUE` and `select = TRUE` if(!missfx) { ## fx set by user if((miss.select <- missing(select)) && any(fx)) { warning("'fx = TRUE' requested; using 'select = FALSE'") select <- FALSE } else if(!miss.select && isTRUE(select)){ stop("fixed d.f. splines ('fx = TRUE') incompatible with 'select = TRUE'") } } ## handle knots - allow vector of length up to two if (length(knots) > 2L) warning("length of 'knots' supplied exceeds '2': using the first two") ## expand knots robustly, no matter what length supplied knots <- rep(knots, length.out = 2) ## handle the bs - we only allow some of the possible options if (length(bs) > 2L) warning("number of basis types supplied exceeds '2': using the first two") bs <- rep(bs, length.out = 2) ## check allowed types BS <- c("tp","ts","cr","cs","ds","ps","ad") want <- match(bs, BS) user.bs <- bs ## store supplied (well expanded supplied ones) bs <- BS[want] if (any(wrong <- is.na(bs))) { stop(gettextf("supplied basis type of '%s' not supported", paste(unique(user.bs[wrong]), collapse = ", "))) } ## can't use "cr", "cs", "ps" in 2-d smoother with s() if(isTRUE(isotropic) && any(bs %in% c("cr", "cs", "ps"))) { stop("bases \"cr\", \"cs\", and \"ps\" not allowed in isotropic smooths") } ## Build formula if (knots[1] <= 0) { f <- formula(y ~ x1 + x2) } else if (knots[1] == 1) { ## why do we treat this differently? f <- formula(y ~ poly(x1, 1) + poly(x2, 1)) } else if (knots[1] == 2) { f <- formula(y ~ poly(x1, 2) + poly(x2, 2) + poly(x1, 1):poly(x2, 1)) } else if (isotropic) { f <- formula(paste0("y ~ s(x1, x2, k = ", knots[1], ", bs = \"", bs[1], "\", fx = ", fx[1],")")) } else { if (any(bs %in% c("ad"))) { ## only "ad" for now, but "fs" should also not be allowed f <- formula(paste0("y ~ s(x1, k = ", knots[1], ", bs = \"", bs[1], "\", fx = ", fx[1], ") + s(x2, k = ", knots[2], ", bs = \"", bs[2], "\", fx = ", fx[2], ")")) } else { f <- formula(paste0("y ~ te(x1, x2, k = c(", paste0(knots, collapse = ", "), "), bs = c(", paste0("\"", bs, "\"", collapse = ", "), "), fx = c(", paste0(fx, collapse = ", "), "))")) } } ## fit model mod <- gam(f, family = family, weights = w, select = select, method = method, gamma = gamma) xn1 <- seq(min(x1), max(x1), len=GRID) xn2 <- seq(min(x2), max(x2), len=GRID) newd <- expand.grid(x1 = xn1, x2 = xn2) fit <- predict(mod, type = "response", newdata=as.data.frame(newd)) poly <- chull(cbind(x1,x2)) ## Move out points of the convex hull to have contour for all data ## points xhull1 <- x1[poly] + sign(x1[poly] - mean(x1[poly])) * diff(range(x1))/(GRID - 1) xhull2 <- x2[poly] + sign(x2[poly] - mean(x2[poly])) * diff(range(x2))/(GRID - 1) npol <- length(poly) np <- nrow(newd) inpoly <- numeric(np) inpoly <- .C(pnpoly, as.integer(npol), as.double(xhull1), as.double(xhull2), as.integer(np), as.double(newd[,1]), as.double(newd[,2]), inpoly = as.integer(inpoly))$inpoly is.na(fit) <- inpoly == 0 if(plot) { if (!add) { if (bubble) { if (is.numeric(bubble)) cex <- bubble cex <- (y - min(y))/diff(range(y)) * (cex-0.4) + 0.4 } plot(X, asp = 1, cex = cex, ...) } if (!missing(main) || (missing(main) && !add)) { if (missing(main)) main <- yname title(main = main) } if (missing(levels)) levels <- pretty(range(fit, finite = TRUE), nlevels) ## Only plot surface is select is FALSE or (TRUE and EDF is diff from 0) if(!select || (select && !isTRUE(all.equal(as.numeric(summary(mod)$edf), 0)))) contour(xn1, xn2, matrix(fit, nrow=GRID), col = col, add = TRUE, levels = levels, labcex = labcex, drawlabels = !is.null(labcex) && labcex > 0, lwd = lwd.cl) } mod$grid <- list(x = xn1, y = xn2, z = matrix(fit, nrow = GRID)) class(mod) <- c("ordisurf", class(mod)) mod }
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordisurf.R