content
stringlengths
0
14.9M
filename
stringlengths
44
136
"print.prestonfit" <- function (x, ...) { cat("\nPreston lognormal model\n") cat("Method:", x$method,"\n") cat("No. of species:", sum(x$freq), "\n\n") print(x$coefficients, ...) cat("\nFrequencies by Octave\n") print(rbind(Observed = x$freq, Fitted = x$fitted), ...) cat("\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.prestonfit.R
"print.procrustes" <- function (x, digits = max(3, getOption("digits") - 3), ...) { cat("\nCall:\n") cat(deparse(x$call), "\n\n") cat("Procrustes sum of squares:\n") cat(formatC(x$ss, digits = digits), "\n\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.procrustes.R
`print.protest` <- function(x, digits = max(3, getOption("digits") - 3), ...) { cat("\nCall:\n") cat(deparse(x$call), "\n\n") cat("Procrustes Sum of Squares (m12 squared): ") cat(formatC(x$ss, digits=digits), "\n") cat("Correlation in a symmetric Procrustes rotation: ") cat(formatC(x$t0, digits = digits), "\n") cat("Significance: ") cat(format.pval(x$signif),"\n\n") cat(howHead(x$control)) cat("\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.protest.R
"print.radfit" <- function(x, digits = max(3, getOption("digits") - 2), ...) { cat("\nRAD models, family", x$family$family, "\n") cat("No. of species ", length(x$y), ", total abundance ", sum(x$y), "\n\n", sep = "") p <- coef(x) if (any(!is.na(p))) p <- formatC(p, format="g", flag = " ", digits = digits) p <- apply(p, 2, function(x) gsub("NA", " ", x)) aic <- sapply(x$models, AIC) bic <- sapply(x$models, AIC, k = log(length(x$y))) dev <- sapply(x$models, deviance) stats <- format(cbind(Deviance = dev, AIC = aic, BIC = bic), digits = digits, ...) out <- cbind(p, stats) print(out, quote=FALSE) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.radfit.R
"print.radfit.frame" <- function (x, ...) { cat("\nDeviance for RAD models:\n\n") out <- sapply(x, function(x) unlist(lapply(x$models, deviance))) printCoefmat(out, na.print = "", ...) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.radfit.frame.R
"print.radline" <- function (x, ...) { cat("\nRAD model:", x$model, "\n") cat("Family:", family(x)$family, "\n") cat("No. of species: ", length(x$y), "\nTotal abundance:", sum(x$y), "\n\n") p <- coef(x) dev <- deviance(x) AIC <- AIC(x) BIC <- AIC(x, k = log(length(x$y))) tmp <- c(p, dev, AIC, BIC) names(tmp) <- c(names(p), "Deviance", "AIC", "BIC") print(tmp, ...) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.radline.R
print.simmat <- function(x, ...) { isSeq <- ifelse(attr(x, "isSeq"), "sequential", "non-sequential") if (attr(x, "binary")) { kind <- "binary" } else { kind <- ifelse(attr(x, "mode") == "integer", "count", "abundance") } d <- dim(x) cat("An object of class", dQuote(class(x)[1L]), "\n") cat(sQuote(attr(x, "method")), " method (", kind, ", ", isSeq, ")\n", sep="") cat(d[1L], "x", d[2L], "matrix\n") cat("Number of permuted matrices =", d[3L], "\n") if (attr(x, "isSeq")) { chainInfo <- "" if (!is.null(attr(x, "chains")) && attr(x, "chains") > 1L) chainInfo <- paste0(" (", attr(x, "chains"), " chains)") cat("Start = ", attr(x, "start"), ", End = ", attr(x, "end"), ", Thin = ", attr(x, "thin"), chainInfo, "\n\n", sep="") } else cat("\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.simmat.R
`print.specaccum` <- function(x, ...) { cat("Species Accumulation Curve\n") if (inherits(x, "fitspecaccum")) cat("Non-linear regression model:", x$SSmodel, "\n") cat("Accumulation method:", x$method) if (x$method == "random") { cat(", with ", ncol(x$perm), " permutations", sep="") } if (!is.null(x$weights)) cat(", weighted") cat("\n") cat("Call:", deparse(x$call), "\n\n") mat <- rbind(Sites = x$sites, Individuals = x$individuals, Effort = x$effort, Richness = x$richness, sd=x$sd) colnames(mat) <- rep("", ncol(mat)) print(zapsmall(mat)) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.specaccum.R
"print.summary.bioenv" <- function(x, ...) { out <- data.frame(size = x$size, correlation = x$cor) rownames(out) <- x$var printCoefmat(out, ...) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.bioenv.R
`print.summary.cca` <- function (x, digits = x$digits, head=NA, tail=head, ...) { hcat <- function(x, head=head, tail=tail, ...) { if (!is.na(head) && !is.na(tail) && head+tail+4 < nrow(x)) x <- rbind(head(x, n=head), "...." = NA, tail(x, n=tail)) print(x, na.print = "", ...) } cat("\nCall:\n") cat(deparse(x$call), "\n") statnam <- if (x$method == "cca") "averages" else "sums" cat("\nPartitioning of ", x$inertia, ":\n", sep = "") out <- c(Total = x$tot.chi, Conditioned = x$partial.chi, Constrained = x$constr.chi, Unconstrained = x$unconst.chi) out <- cbind(Inertia = out, Proportion = out/out[1]) print(out, digits = digits, ...) cat("\nEigenvalues, and their contribution to the", x$inertia, "\n") if (!is.null(x$partial.chi)) { cat("after removing the contribution of conditiniong variables\n") } cat("\n") print(x$cont$importance, ...) if (!is.null(x$concont)) { cat("\nAccumulated constrained eigenvalues\n") print(x$concont$importance, ...) } cat("\nScaling", x$scaling, "for species and site scores\n") if (abs(x$scaling) == 2) { ev.ent <- "Species" other.ent <- "Sites" } else if (abs(x$scaling) == 1) { ev.ent <- "Sites" other.ent <- "Species" } else if (abs(x$scaling) == 3) { ev.ent <- "Both sites and species" other.ent <- NULL } if (x$scaling) { cat("*", ev.ent, "are scaled proportional to eigenvalues\n") if (!is.null(other.ent)) cat("*", other.ent, "are unscaled: weighted dispersion equal") cat(" on all dimensions\n") } if (!x$scaling) { cat("* Both are 'unscaled' or as they are in the result\n") } if (x$scaling < 0) { if (x$method == "cca") cat("* Hill scaling performed on both scores\n") else cat("* Species scores divided by species standard deviations\n") cat(" so that they no longer are biplot scores\n") } if (x$method != "cca") { cat("* General scaling constant of scores: ", attr(x, "const"), "\n") } if (!is.null(x$species)) { cat("\n\nSpecies scores\n\n") hcat(x$species, head=head, tail=tail, digits = digits, ...) } if (!is.null(x$sites)) { cat("\n\nSite scores (weighted", statnam, "of species scores)\n\n") hcat(x$sites, head=head, tail=tail, digits = digits, ...) } if (!is.null(x$constraints)) { cat("\n\nSite constraints (linear combinations of constraining variables)\n\n") hcat(x$constraints, head=head, tail=tail, digits = digits, ...) } if (!is.null(x$biplot)) { cat("\n\nBiplot scores for constraining variables\n\n") print(x$biplot, digits = digits, ...) } if (!is.null(x$centroids) && !is.na(x$centroids[1])) { cat("\n\nCentroids for factor constraints\n\n") print(x$centroids, digits = digits, ...) } cat("\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.cca.R
print.summary.clamtest <- function(x, digits=max(3, getOption("digits") - 3), ...) { cat("Two Groups Species Classification Method (CLAM)\n\n") cat("Specialization threshold =", x$specialization) cat("\nAlpha level =", x$alpha) cat("\n\nEstimated sample coverage:\n") print(x$coverage, digits=digits) cat("\nMinimum abundance for classification:\n") print(structure(c(x$minv[[1]][1,2], x$minv[[2]][1,1]), .Names=x$labels)) cat("\n") printCoefmat(x$summary, digits=digits, ...) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.clamtest.R
`print.summary.decorana` <- function (x, head=NA, tail=head, ...) { digits <- x$digits hcat <- function(x, head=head, tail=tail, ...) { if(!is.na(head) && !is.na(tail) && head + tail + 4 < nrow(x)) x <- rbind(head(x, n=head), "...." = NA, tail(x, n=tail)) printCoefmat(x, na.print="", ...) } if (!is.null(x$spec.scores)) { cat("Species scores:\n\n") TABLE <- cbind(x$spec.scores, Weights = x$spec.priorweights, Totals = x$spec.totals) hcat(TABLE, head=head, tail=tail, digits = digits, ...) cat("\n") } if (!is.null(x$site.scores)) { cat("Site scores:\n\n") TABLE <- cbind(x$site.scores, Totals = x$site.totals) hcat(TABLE, head=head, tail=tail, digits = digits, ...) cat("\n") } invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.decorana.R
`print.summary.isomap` <- function (x, ...) { cat("\nCall:\n") cat(deparse(x$call), "\n\n") cat("Points:\n") print(x$points, ...) cat("\nRetained dissimilarities between points:\n") print(t(x$net), ...) cat("\nRetained", x$nnet, "of", x$ndis, "dissimilarities\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.isomap.R
`print.summary.meandist` <- function(x, ...) { cat("\nMean distances:\n") tab <- rbind("within groups" = x$W, "between groups" = x$B, "overall" = x$D) colnames(tab) <- "Average" print(tab, ...) cat("\nSummary statistics:\n") tab <- rbind("MRPP A weights n" = x$A1, "MRPP A weights n-1" = x$A2, "MRPP A weights n(n-1)"= x$A3, "Classification strength"=x$CS) colnames(tab) <- "Statistic" print(tab, ...) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.meandist.R
## S3 print method for summary.permat `print.summary.permat` <- function(x, digits=2, ...) { n <- attr(x$x, "times") cat("Summary of object of class 'permat'\n\nCall: ") print(x$x$call) cat("\nMatrix type:", attr(x$x, "mtype"), "\nPermutation type:", attr(x$x, "ptype")) cat("\nMethod: ", attr(x$x, "method"), sep = "") if (attr(x$x, "ptype") == "swap") { if (!is.na(attr(x$x, "burnin"))) cat(", burnin: ", attr(x$x, "burnin"), sep = "") if (!is.na(attr(x$x, "thin"))) cat(", thin: ", attr(x$x, "thin"), sep = "") } cat("\nRestricted:", attr(x$x, "is.strat"), "\nFixed margins:", attr(x$x, "fixedmar")) if (!is.na(attr(x$x, "shuffle"))) { if (attr(x$x, "shuffle")=="ind") cat("\nIndividuals") if (attr(x$x, "shuffle")=="samp") cat("\nSamples") if (attr(x$x, "shuffle")=="both") cat("\nIndividuals and samples") cat(" are shuffled") } cat("\n\nMatrix dimensions:", nrow(x$x$orig), "rows,", ncol(x$x$orig), "columns") cat("\nSum of original matrix:", sum(x$x$orig)) cat("\nFill of original matrix:", round(sum(x$x$orig>0)/(nrow(x$x$orig)*ncol(x$x$orig)),digits)) cat("\nNumber of permuted matrices:", n,"\n") cat("\nMatrix sums retained:", round(100 * sum(x$sum) / n, digits), "%") cat("\nMatrix fill retained:", round(100 * sum(x$fill) / n, digits), "%") cat("\nRow sums retained: ", round(100 * sum(x$rowsums) / n, digits), "%") cat("\nColumn sums retained:", round(100 * sum(x$colsums) / n, digits), "%") cat("\nRow incidences retained: ", round(100 * sum(x$browsums) / n, digits), "%") cat("\nColumn incidences retained:", round(100 * sum(x$bcolsums) / n, digits), "%") if (!is.null(x$strsum)) cat("\nSums within strata retained:", round(100 * sum(x$strsum) / n, digits), "%") cat("\n\nBray-Curtis dissimilarities among original and permuted matrices:\n") print(summary(x$bray)) cat("\nChi-squared for original matrix: ", round(attr(x$chisq, "chisq.orig"), digits), "\n", sep = "") cat("Chi-squared values among expected and permuted matrices:\n") print(summary(x$chisq)) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.permat.R
"print.summary.prc" <- function(x, ...) { cat("\nCall:\n") cat(deparse(x$call), "\n") cat("Species scores:\n") print(x$sp, digits=x$digits, ...) cat("\nCoefficients for", paste(x$names[2], "+", paste(x$names, collapse=":")), "interaction\n") cat(paste("which are contrasts to", x$names[2], x$corner, "\n")) cat(paste(c("rows are",", columns are"), x$names[2:1], collapse="")) cat("\n") print(coef(x), digits = x$digits, ...) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.prc.R
"print.summary.procrustes" <- function (x, digits = x$digits, ...) { cat("\nCall:\n") cat(deparse(x$call), "\n") cat("\nNumber of objects:", x$n, " Number of dimensions:", x$k, "\n") cat("\nProcrustes sum of squares: ") cat("\n", formatC(x$ss, digits = digits), "\n") cat("Procrustes root mean squared error: ") cat("\n", formatC(x$rmse, digits = digits), "\n") cat("Quantiles of Procrustes errors:\n") nam <- c("Min", "1Q", "Median", "3Q", "Max") rq <- structure(quantile(x$resid), names = nam) print(rq, digits = digits, ...) cat("\nRotation matrix:\n") print(x$rotation, digits = digits, ...) cat("\nTranslation of averages:\n") print(x$translation, digits = digits, ...) cat("\nScaling of target:\n") print(x$scale, digits = digits, ...) cat("\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.procrustes.R
`print.summary.taxondive` <- function (x, ...) { printCoefmat(x, na.print="", ...) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.summary.taxondive.R
`print.taxondive` <- function (x, ...) { out <- cbind(x$Species, x$D, x$Dstar, x$Lambda, x$Dplus, x$SDplus) out <- rbind(out, Expected = c(NA, x$ED, x$EDstar, NA, x$EDplus, NA)) colnames(out) <- c("Species", "Delta", "Delta*", "Lambda+", "Delta+", "S Delta+") printCoefmat(out, na.print = "") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.taxondive.R
`print.varpart` <- function (x, ...) { cat("\nPartition of", x$inert, "in", x$RDA, "\n\n") writeLines(strwrap(pasteCall(x$call))) if (x$RDA == "RDA") { if (x$scale) cat("Columns of Y were scaled to unit variance\n") if (!is.null(x$transfo)) cat("Species transformation: ", x$transfo) } cat("\n") cat("Explanatory tables:\n") cat(paste(paste(paste("X", seq_along(x$tables), sep=""),": ", x$tables, sep=""), collapse="\n"), "\n\n") print(x$part, ...) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.varpart.R
`print.varpart234` <- function(x, digits = 5, ...) { cat("No. of explanatory tables:", x$nsets, "\n") cat("Total variation (SS):", format(x$SS.Y, digits=digits), "\n") if (x$ordination == "rda") cat(" Variance:", format(x$SS.Y/(x$n-1), digits=digits), "\n") cat("No. of observations:", x$n, "\n") cat("\nPartition table:\n") out <- rbind(x$fract, "Individual fractions" = NA, x$indfract) if (x$nsets > 3) out <- rbind(out, "Controlling 2 tables X" = NA, x$contr2) if (x$nsets > 2) out <- rbind(out, "Controlling 1 table X" = NA, x$contr1) out[,2:3] <- round(out[,2:3], digits=digits) out[,1:4] <- sapply(out[,1:4], function(x) gsub("NA", " ", format(x, digits=digits))) print(out) cat("---\nUse function", sQuote(x$ordination), "to test significance of fractions of interest\n") if (!is.null(x$bigwarning)) for (i in seq_along(x$bigwarning)) warning("collinearity detected: redundant variable(s) between tables ", x$bigwarning[i], "\nresults are probably incorrect: remove redundant variable(s) and repeat the analysis", call. = FALSE) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.varpart234.R
`print.vectorfit` <- function (x, ...) { out <- cbind(x$arrows, r2 = x$r, "Pr(>r)" = x$pvals) printCoefmat(out, na.print = "", zap.ind = seq_len(ncol(out)-2), ...) if (x$permutations) { cat(howHead(x$control)) } invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.vectorfit.R
### support functions for wcmdscale results: print, scores and plot. `print.wcmdscale` <- function(x, digits = max(3, getOption("digits") - 3), ...) { writeLines(strwrap(pasteCall(x$call))) cat("\n") ## tabulate total inertia and ranks totev <- sum(x$eig) negax <- x$eig < 0 if (any(negax)) { ranks <- c(NA, sum(!negax), sum(negax)) negax <- x$eig < 0 realev <- sum(x$eig[!negax]) imev <- sum(x$eig[negax]) evs <- c("Total" = totev, "Real" = realev, "Imaginary" = imev) } else { ranks <- length(x$eig) evs <- c("Total" = totev) } tbl <- cbind("Inertia" = evs, "Rank" = ranks) printCoefmat(tbl, digits = digits, na.print = "") if (!is.na(x$ac) && x$ac > 0) cat("additive constant ", x$ac, " (method ", x$add, ")\n", sep = "") cat("\nResults have", NROW(x$points), "points,", NCOL(x$points), "axes\n") ## print eigenvalues, but truncate very long lists PRINLIM <- 120 neig <- length(x$eig) cat("\nEigenvalues:\n") print(zapsmall(x$eig[1 : min(neig, PRINLIM)], digits = digits, ...)) if (neig > PRINLIM) cat("(Showing", PRINLIM, "of", neig, "eigenvalues)\n") wvar <- var(x$weights) wlen <- length(x$weights) cat("\nWeights:") if (wvar < 1e-6) cat(" Constant\n") else { cat("\n") print(zapsmall(x$weights[1 : min(wlen, PRINLIM)], digits = digits, ...)) if (wlen > PRINLIM) cat("(Showing", PRINLIM, "of", wlen, "weights)\n") } cat("\n") invisible(x) } `scores.wcmdscale` <- function(x, choices = NA, tidy = FALSE, ...) { p <- if (any(is.na(choices))) { x$points } else { choices <- choices[choices <= NCOL(x$points)] x$points[, choices, drop = FALSE] } if (tidy) { p <- data.frame(p, "scores" = "sites", "label" = rownames(p), "weight" = weights(x)) } p } `plot.wcmdscale` <- function(x, choices = c(1,2), type = "t", ...) { ordiplot(x, display = "sites", choices = choices, type = type, ...) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.wcmdscale.R
`procrustes` <- function (X, Y, scale = TRUE, symmetric = FALSE, scores = "sites", ...) { X <- scores(X, display = scores, ...) Y <- scores(Y, display = scores, ...) if (nrow(X) != nrow(Y)) stop(gettextf("matrices have different number of rows: %d and %d", nrow(X), nrow(Y))) if (ncol(X) < ncol(Y)) { warning("X has fewer axes than Y: X adjusted to comform Y\n") addcols <- ncol(Y) - ncol(X) for (i in 1:addcols) X <- cbind(X, 0) } ctrace <- function(MAT) sum(MAT^2) c <- 1 if (symmetric) { X <- scale(X, scale = FALSE) Y <- scale(Y, scale = FALSE) X <- X/sqrt(ctrace(X)) Y <- Y/sqrt(ctrace(Y)) } xmean <- apply(X, 2, mean) ymean <- apply(Y, 2, mean) if (!symmetric) { X <- scale(X, scale = FALSE) Y <- scale(Y, scale = FALSE) } XY <- crossprod(X, Y) sol <- svd(XY) A <- sol$v %*% t(sol$u) if (scale) { c <- sum(sol$d)/ctrace(Y) } Yrot <- c * Y %*% A ## Translation (b) needs scale (c) although Mardia et al. do not ## have this. Reported by Christian Dudel. b <- xmean - c * ymean %*% A R2 <- ctrace(X) + c * c * ctrace(Y) - 2 * c * sum(sol$d) reslt <- list(Yrot = Yrot, X = X, ss = R2, rotation = A, translation = b, scale = c, xmean = xmean, symmetric = symmetric, call = match.call()) reslt$svd <- sol class(reslt) <- "procrustes" reslt }
/scratch/gouwar.j/cran-all/cranData/vegan/R/procrustes.R
`profile.MOStest` <- function(fitted, alpha = 0.01, maxsteps = 10, del = zmax/5, ...) { Pnam <- if(fitted$isHump) "hump" else "pit" k <- coef(fitted$mod) u <- -k[2]/2/k[3] n <- length(residuals(fitted$mod)) std.error <- fieller.MOStest(fitted, level=0.6) std.error <- u - std.error[1] if (is.na(std.error)) std.error <- diff(range(model.matrix(fitted$mod)[,2])) OrigDev <- deviance(fitted$mod) summ <- summary(fitted$mod) DispPar <- summ$dispersion fam <- family(fitted$mod) Y <- fitted$mod$y X <- model.matrix(fitted$mod)[,-3] Xi <- X if (fam$family %in% c("poisson", "binomial", "Negative Binomial")) { zmax <- sqrt(qchisq(1 - alpha/2, 1)) profName <- "z" } else { zmax <- sqrt(qf(1 - alpha/2, 1, n - 1)) profName <- "tau" } zi <- 0 prof <- vector("list", length=1) names(prof) <- Pnam uvi <- u for (sgn in c(-1, 1)) { step <- 0 z <- 0 while((step <- step + 1) < maxsteps && abs(z) < zmax) { ui <- u + sgn * step * del * std.error Xi[,2] <- (X[,2] - ui)^2 fm <- glm.fit(x = Xi, y = Y, family=fam, control = fitted$mod$control) uvi <- c(uvi, ui) zz <- (fm$deviance - OrigDev)/DispPar z <- sgn * sqrt(zz) zi <- c(zi, z) } si <- order(zi) prof[[Pnam]] <- structure(data.frame(zi[si]), names=profName) uvi <- as.matrix(uvi) colnames(uvi) <- Pnam prof[[Pnam]]$par.vals <- uvi[si, , drop=FALSE] } of <- list() of$coefficients <- structure(Pnam, names=Pnam) val <- structure(prof, original.fit = of, summary = summ) class(val) <- c("profile.MOStest", "profile.glm", "profile") val }
/scratch/gouwar.j/cran-all/cranData/vegan/R/profile.MOStest.R
`profile.humpfit` <- function(fitted, parm=1:3, alpha=0.01, maxsteps = 20, del = zmax/5, ...) { INSERT3 <- function(vec, fix, val) { switch(fix, c(val, vec), c(vec[1], val, vec[2]), c(vec, val) ) } HUMP <- function(p, mass, spno, fix, val, ...) { b <- INSERT3(p, fix, val) x <- ifelse(mass < b[1], mass/b[1], b[1]*b[1]/mass/mass) fv <- b[3] * log(1 + b[2]*x/b[3]) n <- wt <- rep(1, length(x)) dev <- sum(dev.resids(spno, fv, wt)) aicfun(spno, n, fv, wt, dev)/2 } dev.resids <- fitted$family$dev.resids aicfun <- fitted$family$aic minll <- fitted$nlm$minimum p <- coefficients(fitted) pv0 <- t(as.matrix(p)) n <- length(fitted$residuals) Pnames <- names(p) summ <- summary(fitted) dispersion <- summ$dispersion std.err <- summ$est[, "Std. Error"] if (summ$family == "poisson") { zmax <- sqrt(qchisq(1 - alpha/2, 3)) profName <- "z" } else { zmax <- sqrt(3 * qf(1 - alpha/2, 3, n-3)) profName <- "tau" } prof <- vector("list", length = length(parm)) names(prof) <- Pnames[parm] for (i in parm) { zi <- 0 par <- pv0 pvi <- pv0[-i] pi <- Pnames[i] for (sgn in c(-1, 1)) { step <- 0 z <- 0 while ((step <- step + 1) < maxsteps && abs(z) < zmax) { bi <- p[i] + sgn * step * del * std.err[i] fm <- nlm(HUMP, p = pvi, mass = fitted$x, spno = fitted$y, fix = i, val = bi) pvi <- fm$estimate ri <- INSERT3(pvi, i, bi) names(ri) <- Pnames par <- rbind(par, ri) zz <- 2*(fm$minimum - minll)/dispersion if (zz > -0.001) zz <- max(0, zz) else stop(gettextf( "profiling found a better solution: original fit had not converged:\n%s: %f", Pnames[i], bi)) z <- sgn*sqrt(zz) zi <- c(zi, z) } } si <- order(zi) prof[[pi]] <- structure(data.frame(zi[si]), names= profName) prof[[pi]]$par.vals <- par[si,] } val <- structure(prof, original.fit = fitted, summary = summ) class(val) <- c("profile.humpfit", "profile.glm", "profile") val }
/scratch/gouwar.j/cran-all/cranData/vegan/R/profile.humpfit.R
`protest` <- function (X, Y, scores = "sites", permutations = how(nperm = 999), ...) { EPS <- sqrt(.Machine$double.eps) X <- scores(X, display = scores, ...) Y <- scores(Y, display = scores, ...) ## Centre and normalize X & Y here so that the permutations will ## be faster X <- scale(X, scale = FALSE) Y <- scale(Y, scale = FALSE) X <- X/sqrt(sum(X^2)) Y <- Y/sqrt(sum(Y^2)) ## Transformed X and Y will yield symmetric procrustes() and we ## need not specify that in the call (but we set it symmetric ## after the call). sol <- procrustes(X, Y, symmetric = FALSE) sol$symmetric <- TRUE sol$t0 <- sqrt(1 - sol$ss) N <- nrow(X) ## Permutations: We only need the goodness of fit statistic from ## Procrustes analysis, and therefore we only have the necessary ## function here. This avoids a lot of overhead of calling ## procrustes() for each permutation. The following gives the ## Procrustes r directly. procr <- function(X, Y) sum(svd(crossprod(X, Y), nv=0, nu=0)$d) permutations <- getPermuteMatrix(permutations, N) if (ncol(permutations) != N) stop(gettextf("'permutations' have %d columns, but data have %d observations", ncol(permutations), N)) np <- nrow(permutations) perm <- sapply(seq_len(np), function(i, ...) procr(X, Y[permutations[i,],])) Pval <- (sum(perm >= sol$t0 - EPS) + 1)/(np + 1) sol$t <- perm sol$signif <- Pval sol$permutations <- np sol$control <- attr(permutations, "control") sol$call <- match.call() class(sol) <- c("protest", "procrustes") sol }
/scratch/gouwar.j/cran-all/cranData/vegan/R/protest.R
"rad.lognormal" <- function (x, family = poisson, ...) { x <- as.rad(x) n <- length(x) rnk <- -qnorm(ppoints(n)) fam <- family(link = "log") ## Must be > 2 species to fit a model if (length(x) > 1) ln <- try(glm(x ~ rnk, family = fam)) if (length(x) < 2) { aic <- NA dev <- rdf <- 0 ln <- nl <- NA p <- rep(NA, 2) fit <- x res <- rep(0, length(x)) wts <- rep(1, length(x)) } else if (inherits(ln, "try-error")) { aic <- rdf <- ln <- nl <- dev <- NA p <- rep(NA, 2) fit <- res <- wts <- rep(NA, length(x)) } else { p <- coef(ln) fit <- fitted(ln) aic <- AIC(ln) rdf <- df.residual(ln) dev <- deviance(ln) res <- ln$residuals wts <- weights(ln) } names(p) <- c("log.mu", "log.sigma") out <- list(model = "Log-Normal", family = fam, y = x, coefficients = p, fitted.values = fit, aic = aic, rank = 2, df.residual = rdf, deviance = dev, residuals = res, prior.weights = wts) class(out) <- c("radline", "glm") out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rad.lognormal.R
"rad.null" <- function(x, family=poisson, ...) { fam <- family(link="log") aicfun <- fam$aic dev.resids <- fam$dev.resids x <- as.rad(x) nsp <- length(x) wt <- rep(1, nsp) if (nsp > 0) { fit <- rev(cumsum(1/nsp:1)/nsp) * sum(x) res <- dev.resids(x, fit, wt) deviance <- sum(res) aic <- aicfun(x, nsp, fit, wt, deviance) } else { fit <- NA aic <- NA res <- NA deviance <- NA } residuals <- x - fit rdf <- nsp names(fit) <- names(x) p <- NA names(p) <- "S" out <- list(model = "Brokenstick", family=fam, y = x, coefficients = p, fitted.values = fit, aic = aic, rank = 0, df.residual = rdf, deviance = deviance, residuals = residuals, prior.weights=wt) class(out) <- c("radline", "glm") out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rad.null.R
"rad.preempt" <- function (x, family = poisson, ...) { canfun <- function(p, x, ...) { if (length(x) <= 1) return(0) p <- plogis(p) if (p == 1) p <- 1 - .Machine$double.eps fv <- linkinv(logJ + log(p) + log(1 - p) * rnk) n <- rep(1, length(fv)) dev <- sum(dev.resids(x, fv, wt)) aicfun(x, n, fv, wt, dev)/2 } fam <- family(link = "log") aicfun <- fam$aic linkinv <- fam$linkinv dev.resids <- fam$dev.resids x <- as.rad(x) nsp <- length(x) rnk <- seq(along = x) - 1 wt <- rep(1, length(x)) logJ <- log(sum(x)) p <- qlogis(0.1) canon <- try(nlm(canfun, p = p, x = x, rnk = rnk, logJ = logJ, wt = wt, hessian = TRUE, ...)) if (inherits(canon, "try-error")) { aic <- rdf <- deviance <- NA p <- rep(NA, 1) fit <- residuals <- wt <- rep(NA, length(x)) } else { if (nsp > 1) { p <- plogis(canon$estimate) fit <- exp(logJ + log(p) + log(1 - p) * rnk) } else { p <- if (nsp > 0) 1 else NA fit <- x } res <- dev.resids(x, fit, wt) deviance <- sum(res) residuals <- x - fit if (nsp > 0) aic <- aicfun(x, rep(1, length(x)), fit, wt, deviance) + 2 else aic <- NA rdf <- length(x) - 1 } names(fit) <- names(x) names(p) <- c("alpha") out <- list(model = "Preemption", family = fam, y = x, coefficients = p, fitted.values = fit, aic = aic, rank = 1, df.residual = rdf, deviance = deviance, residuals = residuals, prior.weights = wt) class(out) <- c("radline", "glm") out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rad.preempt.R
"rad.zipf" <- function (x, family = poisson, ...) { x <- as.rad(x) rnk <- seq(along = x) off <- rep(log(sum(x)), length(x)) fam <- family(link = "log") if (length(x) > 1) ln <- try(glm(x ~ log(rnk) + offset(off), family = fam)) if (length(x) < 2) { aic <- NA dev <- rdf <- 0 ln <- nl <- NA p <- rep(NA, 2) fit <- x res <- rep(0, length(x)) wts <- rep(1, length(x)) } else if (inherits(ln, "try-error")) { aic <- rdf <- ln <- nl <- dev <- NA p <- rep(NA, 2) fit <- res <- wts <- rep(NA, length(x)) } else { fit <- fitted(ln) p <- coef(ln) p[1] <- exp(p[1]) aic <- AIC(ln) rdf <- df.residual(ln) dev <- deviance(ln) res <- ln$residuals wts <- weights(ln) } names(p) <- c("p1", "gamma") out <- list(model = "Zipf", family = fam, y = x, coefficients = p, fitted.values = fit, aic = aic, rank = 2, df.residual = rdf, deviance = dev, residuals = res, prior.weights = wts) class(out) <- c("radline", "glm") out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rad.zipf.R
"rad.zipfbrot" <- function (x, family = poisson, ...) { mandelfun <- function(p, x, ...) { brnk <- log(rnk + exp(p)) sol <- glm(x ~ brnk + offset(off), family = family(link = "log")) -logLik(sol) } x <- as.rad(x) rnk <- seq(along = x) off <- rep(log(sum(x)), length(x)) p <- 0 fam <- family(link = "log") if (length(x) > 2) nl <- try(nlm(mandelfun, p = p, x = x, rnk = rnk, off = off, family = fam, hessian = TRUE, ...)) if (length(x) < 3) { aic <- NA dev <- rdf <- 0 ln <- nl <- NA p <- rep(NA, 3) fit <- x res <- rep(0, length(x)) wts <- rep(1, length(x)) } else if (inherits(nl, "try-error")) { aic <- rdf <- ln <- nl <- dev <- NA p <- rep(NA, 3) fit <- res <- wts <- rep(NA, length(x)) } else { ln <- glm(x ~ log(rnk + exp(nl$estimate)) + offset(off), family = family(link = "log")) fit <- fitted(ln) p <- c(coef(ln), exp(nl$estimate)) p[1] <- exp(p[1]) aic <- AIC(ln) + 2 rdf <- df.residual(ln) - 1 dev <- deviance(ln) res <- ln$residuals wts <- weights(ln) } names(p) <- c("c", "gamma", "beta") out <- list(model = "Zipf-Mandelbrot", family = fam, y = x, coefficients = p, fitted.values = fit, aic = aic, rank = 3, df.residual = rdf, deviance = dev, residuals = res, prior.weights = wts) class(out) <- c("radline", "glm") out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rad.zipfbrot.R
`radfit` <- function (x, ...) { UseMethod("radfit") }
/scratch/gouwar.j/cran-all/cranData/vegan/R/radfit.R
`radfit.data.frame` <- function(x, ...) { ## x *must* have rownames rownames(x) <- rownames(x, do.NULL = TRUE) ## remove empty rows with no species nspec <- specnumber(x) if (any(nspec == 0)) { warning("removed empty rows with no species") x <- x[nspec>0,, drop=FALSE] } out <- apply(x, 1, radfit, ...) if (length(out) == 1) out <- out[[1]] else { class(out) <- "radfit.frame" } out } `radfit.matrix` <- function(x, ...) { radfit(as.data.frame(x), ...) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/radfit.data.frame.R
"radfit.default" <- function (x, ...) { x <- as.rad(x) NU <- rad.null(x, ...) PE <- rad.preempt(x, ...) ##BS <- rad.brokenstick(x, ...) LN <- rad.lognormal(x, ...) ZP <- rad.zipf(x, ...) ZM <- rad.zipfbrot(x, ...) out <- list(y = x, family = PE$family) models <- list(Null = NU, Preemption = PE, Lognormal = LN, Zipf = ZP, Mandelbrot = ZM) out$models <- models class(out) <- "radfit" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/radfit.default.R
`radlattice` <- function(x, BIC = FALSE, ...) { if (!inherits(x, "radfit")) stop("function only works with 'radfit' results for single site") y <- x$y fv <- unlist(fitted(x)) mods <- names(x$models) p <- length(mods) n <- length(y) Abundance <- rep(y, p) Rank <- rep(1:n, p) Model <- factor(rep(mods, each=n), levels = mods) if (BIC) k <- log(length(y)) else k <- 2 aic <- AIC(x, k = k) col <- trellis.par.get("superpose.line")$col if (length(col) > 1) col <- col[2] xyplot(Abundance ~ Rank | Model, subscripts = TRUE, scales = list(y = list(log = 2)), as.table = TRUE, panel = function(x, y, subscripts) { panel.xyplot(x, y, ...) panel.xyplot(x, log2(fv[subscripts]), type="l", lwd=3, col = col, ...) panel.text(max(x), max(y), paste(if (BIC) "BIC" else "AIC", "=", formatC(aic[panel.number()], digits=2, format="f")), pos=2) } ) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/radlattice.R
"rankindex" <- function (grad, veg, indices = c("euc", "man", "gow", "bra", "kul"), stepacross = FALSE, method = "spearman", metric = c("euclidean", "mahalanobis", "manhattan", "gower"), ...) { metric = match.arg(metric) grad <- as.data.frame(grad) if (any(sapply(grad, is.factor))) { span <- daisy(grad) } else { span <- switch(metric, "euclidean" = dist(scale(grad, scale=TRUE)), "mahalanobis" = dist(veganMahatrans(scale(grad, scale=FALSE))), "manhattan" = dist(decostand(grad, "range"), "manhattan"), "gower" = daisy(grad, metric = "gower")) } veg <- as.matrix(veg) res <- numeric(length(indices)) ## create names if indices is a list of functions without names if (is.list(indices)) { nam <- names(indices) if (is.null(nam)) nam <- paste("dis", 1:length(indices), sep="") } else nam <- indices names(res) <- nam ## indices is a list of functions which return dist objects if (is.list(indices)) { for (i in seq_along(indices)) { ## don't accept similarities if (indices[[i]](matrix(1, 2, 2)) != 0) stop("define dissimilarity and not similarity") y <- indices[[i]](veg) ## check class of output if (!inherits(y, "dist")) stop("function in 'indices' must return a 'dist' object") if (stepacross) { is.na(y) <- no.shared(veg) y <- stepacross(y, trace = FALSE, toolong = -1, ...) } res[i] <- cor(span, y, method = method) } ## indices is a character vector naming methods in vegdist } else { for (i in indices) { y <- vegdist(veg, i) if (stepacross) { is.na(y) <- no.shared(veg) y <- stepacross(y, trace = FALSE, toolong = -1, ...) } res[i] <- cor(span, y, method = method) } } res }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rankindex.R
`rarecurve` <- function(x, step = 1, sample, xlab = "Sample Size", ylab = "Species", label = TRUE, col, lty, tidy = FALSE, ...) { ## matrix is faster than data.frame x <- as.matrix(x) ## check input data: must be counts if (!identical(all.equal(x, round(x)), TRUE)) stop("function accepts only integers (counts)") ## should be observed counts minobs <- min(x[x > 0]) if (minobs > 1) warning(gettextf("most observed count data have counts 1, but smallest count is %d", minobs)) ## sort out col and lty if (missing(col)) col <- par("col") if (missing(lty)) lty <- par("lty") tot <- rowSums(x) S <- specnumber(x) ## remove empty rows or we fail if (any(S <= 0)) { message("empty rows removed") x <- x[S > 0,, drop =FALSE] tot <- tot[S > 0] S <- S[S > 0] } nr <- nrow(x) ## rep col and lty to appropriate length col <- rep(col, length.out = nr) lty <- rep(lty, length.out = nr) ## Rarefy out <- lapply(seq_len(nr), function(i) { n <- seq(1, tot[i], by = step) if (n[length(n)] != tot[i]) { ## don't want names on n an `c` adds a name from `tot[i]`) n <- c(n, tot[i], use.names = FALSE) } ## already warned on possibly non-observed counts: do not ## repeat warnings for every row drop(suppressWarnings(rarefy(x[i,], n))) }) ## instead of plotting a rarecurve, return a "tidy" data frame and ## the let the user figure out how to display the results if (tidy) { len <- sapply(out, length) nm <- rownames(x) df <- data.frame( "Site" = factor(rep(nm, len), levels=nm), "Sample" = unlist(lapply(out, attr, which="Subsample")), "Species" = unlist(out)) return(df) # exit with data.frame } Nmax <- sapply(out, function(x) max(attr(x, "Subsample"))) Smax <- sapply(out, max) ## set up plot plot(c(1, max(Nmax)), c(1, max(Smax)), xlab = xlab, ylab = ylab, type = "n", ...) ## rarefied richnesses for given 'sample' if (!missing(sample)) { abline(v = sample) rare <- sapply(out, function(z) approx(x = attr(z, "Subsample"), y = z, xout = sample, rule = 1)$y) abline(h = rare, lwd=0.5) } ## rarefaction curves for (ln in seq_along(out)) { N <- attr(out[[ln]], "Subsample") lines(N, out[[ln]], col = col[ln], lty = lty[ln], ...) } ## label curves at their endpoitns if (label) { ordilabel(cbind(tot, S), labels=rownames(x), ...) } invisible(out) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rarecurve.R
`rarefy` <- function (x, sample, se = FALSE, MARGIN = 1) { x <- as.matrix(x) ## as.matrix changes an n-vector to a n x 1 matrix if (ncol(x) == 1 && MARGIN == 1) x <- t(x) if (!identical(all.equal(x, round(x)), TRUE)) stop("function accepts only integers (counts)") minobs <- min(x[x > 0]) if (minobs > 1) warning(gettextf("most observed count data have counts 1, but smallest count is %d", minobs)) minsample <- min(apply(x, MARGIN, sum)) if (missing(sample)) { stop( gettextf( "the size of 'sample' must be given --\nHint: Smallest site maximum %d", minsample)) } if (any(sample > minsample)) warning( gettextf( "requested 'sample' was larger than smallest site maximum (%d)", minsample)) rarefun <- function(x, sample) { x <- x[x > 0] J <- sum(x) ldiv <- lchoose(J, sample) p1 <- ifelse(J - x < sample, 0, exp(lchoose(J - x, sample) - ldiv)) out <- sum(1 - p1) if (se) { V <- sum(p1 * (1 - p1)) Jxx <- J - outer(x, x, "+") ind <- lower.tri(Jxx) Jxx <- Jxx[ind] V <- V + 2 * sum(ifelse(Jxx < sample, 0, exp(lchoose(Jxx, sample) - ldiv)) - outer(p1, p1)[ind]) ## V is >= 0, but numerical zero can be negative (e.g, ## -1e-16), and we avoid taking its square root out <- cbind(out, sqrt(max(V, 0))) } out } if (length(sample) > 1) { S.rare <- sapply(sample, function(n) apply(x, MARGIN, rarefun, sample = n)) S.rare <- matrix(S.rare, ncol=length(sample)) colnames(S.rare) <- paste("N", sample, sep="") if (se) { dn <- unlist(dimnames(x)[MARGIN]) rownames(S.rare) <- paste(rep(dn, each=2), c("S","se"), sep=".") } } else { S.rare <- apply(x, MARGIN, rarefun, sample = sample) if (se) rownames(S.rare) <- c("S", "se") } attr(S.rare, "Subsample") <- sample S.rare }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rarefy.R
#' Slope of Rarefunction Curve at Given Sample Size #' #' Function evaluates the derivative of the rarefaction #' function at given sample size. The derivative was #' directly derived from the expression used in \code{rarefy}. #' #' @param x Community counts, either an integer vector for a single #' site or a data frame or matrix with each row giving site vectors. #' @param sample Sample sizes where the derivatives are evaluated; can #' be real #' `rareslope` <- function(x, sample) { ## 'x' must be integers ('sample' need not be) if (!identical(all.equal(x, round(x)), TRUE)) stop("community data 'x' must be integers (counts)") minobs <- min(x[x > 0]) if (minobs > 1) warning(gettextf("most observed count data have counts 1, but smallest count is %d", minobs)) slope <- function(x, sample) { x <- x[x>0] J <- sum(x) ## Replace Hurlbert's factorials with gamma() functions and do ## some algebra for derivatives. NB., rarefy() does not use ## factorials but lchoose directly. d <- digamma(pmax(J-sample+1, 1)) - digamma(pmax(J-x-sample+1, 1)) g <- lgamma(pmax(J-x+1, 1)) + lgamma(pmax(J-sample+1, 1)) - lgamma(pmax(J-x-sample+1, 1)) - lgamma(J+1) d <- d*exp(g) sum(d[is.finite(d)]) } if (length(dim(x)) == 2) out <- sapply(sample, function(n) apply(x, 1, slope, sample = n)) else out <- sapply(sample, function(n) slope(x, sample=n)) out <- drop(out) if (length(sample) > 1) { if (is.matrix(out)) colnames(out) <- paste0("N", sample) else names(out) <- paste0("N", sample) } out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rareslope.R
`raupcrick` <- function(comm, null = "r1", nsimul = 999, chase = FALSE, ...) { comm <- as.matrix(comm) comm <- ifelse(comm > 0, 1, 0) ## 'tri' is a faster alternative to as.dist(): it takes the lower ## diagonal, but does not set attributes of a "dist" object N <- nrow(comm) tri <- matrix(FALSE, N, N) tri <- row(tri) > col(tri) ## function(x) designdist(x, "J", terms="binary") does the same, ## but is much slower sol <- oecosimu(comm, function(x) tcrossprod(x)[tri], method = null, nsimul = nsimul, alternative = if (chase) "less" else "greater", ...) ## Chase et al. way, or the standard way if (chase) out <- 1 - sol$oecosimu$pval else out <- sol$oecosimu$pval ## set attributes of a "dist" object attributes(out) <- list("class"=c("raupcrick", "dist"), "Size"=N, "Labels" = rownames(comm), "maxdist" = 1, "call" = match.call(), "Diag" = FALSE, "Upper" = FALSE, "method" = "raupcrick") out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/raupcrick.R
"rda" <- function (...) { UseMethod("rda") }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rda.R
`rda.default` <- function (X, Y = NULL, Z = NULL, scale = FALSE, ...) { ## Protect against grave misuse: some people have used ## dissimilarities instead of data if (inherits(X, "dist") || NCOL(X) == NROW(X) && isTRUE(all.equal(X, t(X)))) stop("function cannot be used with (dis)similarities") X <- as.matrix(X) if (!is.null(Y)) { if (is.data.frame(Y) || is.factor(Y)) Y <- model.matrix(~ ., as.data.frame(Y))[,-1,drop=FALSE] Y <- as.matrix(Y) } if (!is.null(Z)) { if (is.data.frame(Z) || is.factor(Z)) Z <- model.matrix(~ ., as.data.frame(Z))[,-1,drop=FALSE] Z <- as.matrix(Z) } sol <- ordConstrained(X, Y, Z, arg = scale, method = "rda") call <- match.call() call[[1]] <- as.name("rda") sol$call <- call inertia <- if (scale) "correlations" else "variance" sol <- c(sol, list("inertia" = inertia)) ## package klaR also has rda(): add a warning text that will be ## printed if vegan::rda object is displayed with klaR:::print.rda sol$regularization <- "this is a vegan::rda result object" class(sol) <- c("rda", "cca") sol }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rda.default.R
`rda.formula` <- function (formula, data, scale = FALSE, na.action = na.fail, subset = NULL, ...) { if (missing(data)) { data <- parent.frame() } else { data <- eval(match.call()$data, environment(formula), enclos = .GlobalEnv) } d <- ordiParseFormula(formula, data = data, na.action = na.action, subset = substitute(subset)) sol <- rda.default(d$X, d$Y, d$Z, scale) if (!is.null(sol$CCA) && sol$CCA$rank > 0) { centroids <- centroids.cca(sol$CCA$wa, d$modelframe) if (!is.null(sol$CCA$alias)) centroids <- unique(centroids) if (!is.null(centroids)) { rs <- rowSums(centroids^2) centroids <- centroids[rs > 1e-04,, drop = FALSE] if (length(centroids) == 0) centroids <- NULL } if (!is.null(centroids)) sol$CCA$centroids <- centroids } ## replace rda.default call call <- match.call() call[[1]] <- as.name("rda") call$formula <- formula(d$terms) sol$call <- call if (!is.null(d$na.action)) { sol$na.action <- d$na.action sol <- ordiNAexclude(sol, d$excluded) } if (!is.null(d$subset)) sol$subset <- d$subset ## drops class in c() sol <- c(sol, list(terms = d$terms, terminfo = ordiTerminfo(d, d$modelframe))) class(sol) <- c("rda", "cca") sol }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rda.formula.R
### Reads condensed CEP and similar CANOCO formatted data ### This function was originally based on Fortran code to interpret ### the format and read the data, but Fortran I/O is no longer allowed ### in CRAN packages. The original Fortran version was made available ### in github package vegandevs/cepreaded. This function uses ### utils::read.fortran. For that function we must translate the ### Fortran format in form understood by read.fortran(). This may ### fail, and read.fortran() can also fail, in particular wih ### interpreting the length of decimal part in F format. ### The original Fortran (and cepreader) can also interpret open ### (ordinary) Fortran format and Canoco FREE format, but this ### function currently only reads condensed data. `read.cep` <- function (file, positive = TRUE) { ## Read all file first, interpret contents later cep <- readLines(file) ## skip first line and get the format i <- 2 fmt <- substr(cep[i], 1, 60) # CEP sets fmt in cols 1-60 fmt <- toupper(fmt) fmt <- gsub(" ", "", fmt) ## get the number of data entries per record nrecord <- as.numeric(substr(cep[i], 61,80)) if (is.na(nrecord)) { i <- i+1 nrecord <- as.numeric(cep[i]) } ## check format: there should be to I-elements (site id, species ## id), and there should be two opening "(" fmt1 <- strsplit(fmt, NULL)[[1]] if (sum(fmt1 == "I") != 2 || (nrecord > 1 && sum(fmt1 == "(") != 2)) stop(gettextf("format %s does not look correct for condensed data", fmt)) ## process format: basically the format should have elements for ## (INT, n(INT, REAL)). read.fortran() does not understand ## multiplier 'n', but we need to rep((INT,REAL), n) in the ## fmt vector. fmt <- gsub(paste0(nrecord, "\\("), ";", fmt) # separate with ; fmt <- gsub("\\(","",fmt) fmt <- gsub("\\)","",fmt) ## number of decimals: there should be one and only one Fa.b ## format, and we need 'b' ndec <- as.numeric(strsplit(fmt, "\\.")[[1]][2]) ## now split format for plotid and nrecord couplets fmt <- strsplit(fmt, ";")[[1]] fmt <- c(strsplit(fmt[1], ",")[[1]], rep(strsplit(fmt[2], ",")[[1]], nrecord)) if (any(is.na(fmt))) fmt <- fmt[!is.na(fmt)] ## vectors to store results (with safe size) nlines <- length(cep)-i siteid <- numeric(nlines * nrecord) specid <- numeric(nlines * nrecord) abund <- numeric(nlines * nrecord) ids <- seq(2, by=2, len=nrecord) id <- 0 ## read until there an empty siteid repeat { i <- i+1 x <- drop(as.matrix(read.fortran(textConnection(cep[i]), fmt))) if(is.na(x[1]) || x[1] <= 0) break for(j in ids) { if(!is.na(x[j])) { id <- id+1 siteid[id] <- x[1] specid[id] <- x[j] abund[id] <- x[j+1] } else break } } ## check there are no duplicate entries: only last one would be ## used, and this causes an error (and this has happened in ## literature) if (any(dups <- duplicated(cbind(siteid, specid))[seq_len(id)])) stop("you have duplicated data entries: ", paste(siteid[seq_len(id)][dups], specid[seq_len(id)][dups], collapse = ", ")) ## max identifiers nsp <- max(specid) nst <- max(siteid) ## read dimnames i <- i+1 nomina <- read.fwf(textConnection(cep[i:length(cep)]), rep(8, 10), as.is=TRUE) nomina <- gsub(" ", "", as.vector(t(nomina))) spnam <- make.names(nomina[seq_len(nsp)], unique = TRUE) nst0 <- ceiling(nsp/10) * 10 stnam <- make.names(nomina[seq_len(nst) + nst0], unique = TRUE) ## utils::read.fortran divides with 10^ndec of F format even when ## there is an explicit decimal point: undo if this seems to have ## happened if (ndec > 0 && min(abund[1:id]) <= 10^(-ndec)) abund <- abund * 10^ndec ## make as a matrix out <- matrix(0, nst, nsp) for(j in seq_len(id)) out[siteid[j], specid[j]] <- abund[j] dimnames(out) <- list(stnam, spnam) if (positive) { rs <- rowSums(out) cs <- colSums(out) if (any(cs <= 0) || any(rs <= 0)) out <- out[rs > 0, cs > 0] } as.data.frame(out) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/read.cep.R
`renyi` <- function (x, scales = c(0, 0.25, 0.5, 1, 2, 4, 8, 16, 32, 64, Inf), hill = FALSE) { x <- as.matrix(x) n <- nrow(x) p <- ncol(x) if (p == 1) { x <- t(x) n <- nrow(x) p <- ncol(x) } ## scale rows to unit total x <- sweep(x, 1, rowSums(x), "/") m <- length(scales) result <- array(0, dim = c(n, m)) dimnames(result) <- list(sites = rownames(x), scale = scales) for (a in 1:m) { result[,a] <- switch(as.character(scales[a]), "0" = log(rowSums(x > 0)), "1" = -rowSums(x * log(x), na.rm = TRUE), "2" = -log(rowSums(x^2)), "Inf" = -log(apply(x, 1, max)), log(rowSums(x^scales[a]))/(1 - scales[a])) } if (hill) result <- exp(result) if (any(dim(result) == 1)) result <- drop(result) else result <- as.data.frame(result) class(result) <- c("renyi", class(result)) result }
/scratch/gouwar.j/cran-all/cranData/vegan/R/renyi.R
`renyiaccum` <- function(x, scales=c(0, 0.5, 1, 2, 4, Inf), permutations = 100, raw = FALSE, collector = FALSE, subset, ...) { if (!missing(subset)) x <- subset(x, subset) x <- as.matrix(x) n <- nrow(x) p <- ncol(x) if (p==1) { x <- t(x) n <- nrow(x) p <- ncol(x) } pmat <- getPermuteMatrix(permutations, n) permutations <- nrow(pmat) m <- length(scales) result <- array(dim=c(n,m,permutations)) dimnames(result) <- list(pooled.sites=c(1:n), scale=scales, permutation=c(1:permutations)) for (k in 1:permutations) { result[,,k] <- as.matrix(renyi((apply(x[pmat[k,],],2,cumsum)), scales=scales, ...)) } if (raw) collector <- FALSE if (collector) ref <- as.matrix(renyi(apply(x, 2, cumsum), scales = scales, ...)) if (raw) { if (m==1) { result <- result[,1,] } }else{ tmp <- array(dim=c(n,m,6 + as.numeric(collector))) for (i in 1:n) { for (j in 1:m) { tmp[i,j,1] <- mean(result[i,j,1:permutations]) tmp[i,j,2] <- sd(result[i,j,1:permutations]) tmp[i,j,3] <- min(result[i,j,1:permutations]) tmp[i,j,4] <- max(result[i,j,1:permutations]) tmp[i,j,5] <- quantile(result[i,j,1:permutations],0.025) tmp[i,j,6] <- quantile(result[i,j,1:permutations],0.975) if (collector) tmp[i,j,7] <- ref[i,j] } } result <- tmp dimnames(result) <- list(pooled.sites=c(1:n), scale=scales, c("mean", "stdev", "min", "max", "Qnt 0.025", "Qnt 0.975", if (collector) "Collector")) } attr(result, "control") <- attr(pmat, "control") class(result) <- c("renyiaccum", class(result)) result }
/scratch/gouwar.j/cran-all/cranData/vegan/R/renyiaccum.R
"residuals.cca" <- function(object, ...) fitted(object, model = "CA", ...)
/scratch/gouwar.j/cran-all/cranData/vegan/R/residuals.cca.R
`residuals.procrustes` <- function (object, ...) { distance <- object$X - object$Yrot resid <- rowSums(distance^2) sqrt(resid) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/residuals.procrustes.R
### Random rarefied subsample: sample without replacement `rrarefy` <- function(x, sample) { x <- as.matrix(x) if (!identical(all.equal(x, round(x)), TRUE)) stop("function is meaningful only for integers (counts)") ## x may not be exactly integer, since, e.g., sqrt(2)^2 != 2 if (!is.integer(x)) x <- round(x) minobs <- min(x[x > 0]) if (minobs > 1) warning(gettextf("function should be used for observed counts, but smallest count is %d", minobs)) if (ncol(x) == 1) x <- t(x) if (length(sample) > 1 && length(sample) != nrow(x)) stop(gettextf( "length of 'sample' and number of rows of 'x' do not match")) sample <- rep(sample, length=nrow(x)) ## warn if something cannot be rarefied if (any(rowSums(x) < sample)) warning("some row sums < 'sample' and are not rarefied") for (i in 1:nrow(x)) { x[i,] <- .Call(do_rrarefy, x[i,], sample[i]) } x } ### Probabilities that species occur in a rarefied 'sample' `drarefy` <- function(x, sample) { if (!identical(all.equal(x, round(x)), TRUE)) stop("function accepts only integers (counts)") minobs <- min(x[x > 0]) if (minobs > 1) warning(gettextf("most observed count data have counts 1, but smallest count is %d", minobs)) if (length(sample) > 1 && length(sample) != nrow(x)) stop(gettextf( "length of 'sample' and number of rows of 'x' do not match")) x <- drop(as.matrix(x)) ## warn on too large samples if (is.matrix(x)) rs <- rowSums(x) else rs <- sum(x) if (any(rs < sample)) warning("some row sums < 'sample' and probabilities either 0 or 1") ## dfun is kluge: first item of vector x must be the sample size, ## and the rest is the community data. This seemed an easy trick ## to evaluate dfun in an apply() instead of a loop. dfun <- function(x) { J <- sum(x[-1]) sample <- min(x[1], J) 1 - exp(lchoose(J - x[-1], sample) - lchoose(J, sample)) } if (length(dim(x)) > 1) t(apply(cbind(sample, x), 1, dfun)) else dfun(c(sample, x)) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/rrarefy.R
##' @title Utility for handling user friendly scaling --- None exported ##' ##' @description Convert user-friendly descriptions of scalings to numeric codes used by \code{scores} to date. ##' ##' @param scaling character or numeric; which type of scaling is required? Numeric values are returned unaltered ##' @param correlation logical; should correlation-like scores be returned? ##' @param hill logical; should Hill's scaling scores be returned? `scalingType` <- function(scaling = c("none", "sites", "species", "symmetric"), correlation = FALSE, hill = FALSE) { ## Only process scaling further if it is character if (is.numeric(scaling)) { return(scaling) # numeric; return early } else if (is.character(scaling)) { ## non-numeric scaling: change to correct numeric code scaling <- match.arg(scaling) # match user choice ## Keep `tab` as this is the order of numeric codes ## Allows potential to change the default ordering of formal argument 'scaling' tab <- c("none", "sites", "species", "symmetric") scaling <- match(scaling, tab) - 1 # -1 as none == scaling 0 if (correlation || hill) { scaling <- -scaling } } else { stop("'scaling' is not 'numeric' nor 'character'.") } scaling # return }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scalingUtils.R
"scores" <- function(x, ...) UseMethod("scores")
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.R
`scores.betadisper` <- function(x, display = c("sites", "centroids"), choices = c(1,2), ...) { display <- match.arg(display, several.ok = TRUE) sol <- list() if("sites" %in% display) sol$sites <- x$vectors[, choices] if("centroids" %in% display) { if(is.matrix(x$centroids)) sol$centroids <- x$centroids[, choices, drop = FALSE] else sol$centroids <- matrix(x$centroids[choices], ncol = length(choices), byrow = TRUE) } if (length(sol) == 1) sol <- sol[[1]] sol }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.betadisper.R
`scores.betadiver` <- function(x, triangular = TRUE, ...) { if (triangular) { tot <- x$a + x$b + x$c a <- x$a/tot c <- x$c/tot y <- sqrt(0.75)*a x <- c + a/2 out <- cbind(x, y) } else { out <- sapply(x, cbind) } out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.betadiver.R
`scores.cca` <- function (x, choices = c(1, 2), display = c("sp", "wa", "bp", "cn"), scaling = "species", hill = FALSE, tidy = FALSE, ...) { ## Check the na.action, and pad the result with NA or WA if class ## "exclude" if (!is.null(x$na.action) && inherits(x$na.action, "exclude")) x <- ordiNApredict(x$na.action, x) tabula <- c("species", "sites", "constraints", "biplot", "regression", "centroids") names(tabula) <- c("sp", "wa", "lc", "bp", "reg", "cn") if (is.null(x$CCA)) tabula <- tabula[1:2] display <- match.arg(display, c("sites", "species", "wa", "lc", "bp", "reg", "cn", "all"), several.ok = TRUE) ## set "all" for tidy scores if (tidy) display <- "all" if("sites" %in% display) display[display == "sites"] <- "wa" if("species" %in% display) display[display == "species"] <- "sp" if("all" %in% display) display <- names(tabula) take <- tabula[display] slam <- sqrt(c(x$CCA$eig, x$CA$eig)[choices]) rnk <- x$CCA$rank sol <- list() ## process scaling; numeric scaling will just be returned as is scaling <- scalingType(scaling = scaling, hill = hill) if ("species" %in% take) { v <- cbind(x$CCA$v, x$CA$v)[, choices, drop = FALSE] if (scaling) { scal <- list(1, slam, sqrt(slam))[[abs(scaling)]] v <- sweep(v, 2, scal, "*") if (scaling < 0) { scal <- sqrt(1/(1 - slam^2)) v <- sweep(v, 2, scal, "*") } } sol$species <- v } if ("sites" %in% take) { wa <- cbind(x$CCA$wa, x$CA$u)[, choices, drop = FALSE] if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] wa <- sweep(wa, 2, scal, "*") if (scaling < 0) { scal <- sqrt(1/(1 - slam^2)) wa <- sweep(wa, 2, scal, "*") } } sol$sites <- wa } if ("constraints" %in% take) { u <- cbind(x$CCA$u, x$CA$u)[, choices, drop = FALSE] if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] u <- sweep(u, 2, scal, "*") if (scaling < 0) { scal <- sqrt(1/(1 - slam^2)) u <- sweep(u, 2, scal, "*") } } sol$constraints <- u } if ("biplot" %in% take && !is.null(x$CCA$biplot)) { b <- matrix(0, nrow(x$CCA$biplot), length(choices)) b[, choices <= rnk] <- x$CCA$biplot[, choices[choices <= rnk]] colnames(b) <- c(colnames(x$CCA$u), colnames(x$CA$u))[choices] rownames(b) <- rownames(x$CCA$biplot) if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] b <- sweep(b, 2, scal, "*") } sol$biplot <- b } if ("regression" %in% take) { b <- coef(x, norm = TRUE) reg <- matrix(0, nrow(b), length(choices)) reg[, choices <= rnk] <- b[, choices[choices <= rnk]] dimnames(reg) <- list(rownames(b), c(colnames(x$CCA$u), colnames(x$CA$u))[choices]) if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] reg <- sweep(reg, 2, scal, "*") } sol$regression <- reg } if ("centroids" %in% take) { if (is.null(x$CCA$centroids)) sol$centroids <- NULL else { cn <- matrix(0, nrow(x$CCA$centroids), length(choices)) cn[, choices <= rnk] <- x$CCA$centroids[, choices[choices <= rnk]] colnames(cn) <- c(colnames(x$CCA$u), colnames(x$CA$u))[choices] rownames(cn) <- rownames(x$CCA$centroids) if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] cn <- sweep(cn, 2, scal, "*") if (scaling < 0) { scal <- sqrt(1/(1 - slam^2)) cn <- sweep(cn, 2, scal, "*") } } sol$centroids <- cn } } ## Take care that scores have names if (length(sol)) { for (i in seq_along(sol)) { if (is.matrix(sol[[i]])) rownames(sol[[i]]) <- rownames(sol[[i]], do.NULL = FALSE, prefix = substr(names(sol)[i], 1, 3)) } } ## tidy scores if (tidy) { if (length(sol) == 0) # no requested scores existed return(NULL) ## re-group biplot arrays duplicating factor centroids if (!is.null(sol$biplot) && !is.null(sol$centroids)) { dup <- rownames(sol$biplot) %in% rownames(sol$centroids) if (any(dup)) { sol$factorbiplot <- sol$biplot[dup,, drop=FALSE] sol$biplot <- sol$biplot[!dup,, drop=FALSE] } } group <- sapply(sol, nrow) group <- rep(names(group), group) sol <- do.call(rbind, sol) label <- rownames(sol) rw <- x$rowsum # weights(x) can fail with na.action=na.exclude cw <- weights(x, "species") w <- rep(NA, nrow(sol)) if (any(weighted <- group == "sites")) w[weighted] <- rw if (any(weighted <- group == "constraints")) w[weighted] <- rw if (any(weighted <- group == "species")) w[weighted] <- cw sol <- as.data.frame(sol) sol$score <- as.factor(group) sol$label <- label sol$weight <- w } ## return NULL instead of list(), and matrix instead of a list of ## one matrix switch(min(2, length(sol)), sol[[1]], sol) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.cca.R
`scores.decorana` <- function (x, display="sites", choices = 1:4, origin=TRUE, tidy = FALSE, ...) { display <- match.arg(display, c("sites", "species", "both"), several.ok = TRUE) ## return "both" in tidy scores if(tidy) display <- "both" out <- list() if(any(c("sites", "both") %in% display)) { sites <- x$rproj if (origin) sites <- sweep(sites, 2, x$origin, "-") out$sites <- sites[, choices, drop=FALSE] } if(any(c("species", "both") %in% display)) { species <- x$cproj if (origin) species <- sweep(species, 2, x$origin, "-") out$species <- species[, choices] } if (tidy) { if (length(out) == 0) # no scores (never TRUE?) return(NULL) group <- sapply(out, nrow) group <- rep(names(group), group) out <- do.call(rbind, out) label <- rownames(out) out <- as.data.frame(out) out$score <- group out$label <- label wts <- rep(NA, nrow(out)) if (any(take <- group == "sites")) wts[take] <- weights(x, display="sites") if (any(take <- group == "species")) wts[take] <- weights(x, display="species") out$weight <- wts } ## two kind of scores: return NULL, matrix or a list if (length(out) == 1) out[[1]] else out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.decorana.R
"scores.default" <- function (x, choices, display = c("sites", "species", "both"), tidy = FALSE, ...) { display <- match.arg(display) X <- Y <- NULL if (tidy) display <- "both" att <- names(x) if (is.data.frame(x) && all(sapply(x, is.numeric))) x <- as.matrix(x) if (is.list(x) && display %in% c("sites", "both")) { if ("points" %in% att) X <- x$points else if ("rproj" %in% att) X <- x$rproj else if ("x" %in% att) X <- x$x else if ("scores" %in% att) X <- x$scores else if ("sites" %in% att) X <- x$sites else if("li" %in% att) X <- x$li else if("l1" %in% att) X <- x$l1 else stop("cannot find scores") } if (is.list(x) && display %in% c("species", "both")) { if ("species" %in% att) Y <- x$species else if ("cproj" %in% att) Y <- x$cproj else if ("rotation" %in% att) Y <- x$rotation else if ("loadings" %in% att) Y <- x$loadings else if ("co" %in% att) Y <- x$co else if ("c1" %in% att) Y <- x$c1 else if (display == "species") # fail if species explicitly requested stop("cannot find species scores") else { # "both" may be non-chalant: only warn warning("cannot find species scores") } } else if (is.numeric(x)) { X <- as.matrix(x) ## as.matrix() changes a score vector to 1-col matrix: this is ## a hack which may fail sometimes (but probably less often ## than without this hack): ## Removed this hack after an issue raised by ## vanderleidebastiani in github. He was worried for getting ## an error when 'choices' were not given with genuinely 1-dim ## (1-col) results. At a second look, it seems that this hack ## will fail both with missing 'choices', and also often with ## 'choices' given because 'choices' are only applied later, ## so that nrow(X) > length(choices). Only vectors (dim arg ## missing) should fail here. Let's see... ##if (ncol(X) == 1 && nrow(X) == length(choices)) ## X <- t(X) } if (!is.null(X) && NROW(X) && is.null(rownames(X))) { rownames(X) <- paste0("site", 1:nrow(X)) } if (!is.null(Y) && NROW(Y) && is.null(rownames(Y))) { rownames(Y) <- paste0("spec", 1:nrow(Y)) } if (!is.null(X) && NCOL(X) && is.null(colnames(X))) { colnames(X) <- paste0("Dim", 1:ncol(X)) } if (!is.null(Y) && NCOL(Y) && is.null(colnames(Y))) { colnames(Y) <- paste0("Dim", 1:ncol(Y)) } if (!missing(choices)) { if (!is.null(X)) X <- X[, choices[choices <= NCOL(X)], drop = FALSE] if (!is.null(Y)) Y <- Y[, choices[choices <= NCOL(Y)], drop = FALSE] } out <- list("sites" = X, "species" = Y) if (tidy) { score <- sapply(out, NROW) out <- data.frame(do.call(rbind, out), "scores" = rep(names(score), score)) out$label <- rownames(out) } if (any(drop <- sapply(out, is.null))) { out <- out[!drop] if (is.list(out) && length(out) == 1) out <- out[[1]] } out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.default.R
`scores.envfit` <- function (x, display, choices, arrow.mul = 1, tidy = FALSE, ...) { display <- match.arg(display, c("vectors", "bp", "factors", "cn"), several.ok = TRUE) out <- list() if (any(display %in% c("vectors", "bp"))) { vects <- x$vectors$arrows[, , drop = FALSE] if (!missing(choices)) vects <- vects[, choices, drop=FALSE] if (!is.null(vects)) out$vectors <- arrow.mul * sqrt(x$vectors$r) * vects } if (any(display %in% c("factors", "cn"))) { facts <- x$factors$centroids[, , drop = FALSE] if (!missing(choices)) facts <- facts[, choices, drop=FALSE] out$factors <- facts } if (tidy) { if (length(out) == 0) # no scores return(NULL) group <- sapply(out, nrow) group <- rep(names(group), group) out <- do.call(rbind, out) label <- rownames(out) out <- as.data.frame(out) out$score <- group out$label <- label } ## only two kind of scores: return NULL, matrix or a list switch(length(out), out[[1]], out) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.envfit.R
`scores.lda` <- function(x, display, ...) { display <- match.arg(display, c("sites", "species", "scores", "predictors", "x", "coef"), several.ok = TRUE) out <- NULL if (display %in% c("sites", "scores", "x")) out[["scores"]] <- predict(x)$x if (display %in% c("species", "predictors", "coef")) out[["coefficients"]] <- coef(x) if (length(out) == 1) out <- out[[1]] out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.lda.R
`scores.metaMDS` <- function(x, display = c("sites", "species"), shrink = FALSE, choices, tidy = FALSE, ...) { display <- match.arg(display, c("sites","species"), several.ok = TRUE) if (missing(choices)) choices <- seq_len(x$ndim) else choices <- choices[choices <= x$ndim] out <- list() if ("sites" %in% display) { sites <- x$points[, choices, drop=FALSE] colnames(sites) <- paste0("NMDS", choices) out$sites <- sites } if ("species" %in% display && !is.null(x$species) && !all(is.na(x$species))) { species <- x$species[, choices, drop=FALSE] colnames(species) <- paste0("NMDS", choices) if (shrink) { ## [,choices] drops attributes mul <- sqrt(attr(x$species, "shrinkage")) cnt <- attr(x$species, "centre") if (is.null(mul)) message("species are not shrunken, because they were not expanded") else { mul <- mul[choices] cnt <- cnt[choices] species <- sweep(species, 2, cnt, "-") species <- sweep(species, 2, mul, "*") species <- sweep(species, 2, cnt, "+") } } out$species <- species } if (tidy) { if (length(out) == 0) # no scores (species scores may not exist) return(NULL) group <- sapply(out, nrow) group <- rep(names(group), group) out <- do.call(rbind, out) label <- rownames(out) out <- as.data.frame(out) out$score <- group out$label <- label } ## only two kind of scores, return NULL, matrix, or a list of scores if (length(out) == 1) out[[1]] else out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.metaMDS.R
## Extract the points in the hull as a one matrix `scores.ordihull` <- function(x, ...) { out <- NULL for(i in seq_along(x)) out <- rbind(out, x[[i]]) hulls <- rep(names(x), sapply(x, function(z) NROW(z))) attr(out, "hulls") <- hulls out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.ordihull.R
`scores.ordiplot` <- function (x, display = "sites", ...) { if (length(x) == 1) return(x[[1]]) items <- names(x) items <- items[!is.na(items)] display <- match.arg(display, items) x <- x[[display]] attr(x, "score") <- display x }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.ordiplot.R
`scores.orditkplot` <- function(x, display, ...) { if (!missing(display) && !is.na(pmatch(display, "labels"))) x$labels else x$points }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.orditkplot.R
`scores.pcnm` <- function(x, choices, ...) { if (missing(choices)) x$vectors else x$vectors[, choices] }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.pcnm.R
### extract scores from rda, capscale and dbrda results. The two ### latter can have special features which are commented below. cca ### results are handled by scores.cca. `scores.rda` <- function (x, choices = c(1, 2), display = c("sp", "wa", "bp", "cn"), scaling = "species", const, correlation = FALSE, tidy = FALSE, ...) { ## Check the na.action, and pad the result with NA or WA if class ## "exclude" if (!is.null(x$na.action) && inherits(x$na.action, "exclude")) x <- ordiNApredict(x$na.action, x) tabula <- c("species", "sites", "constraints", "biplot", "regression", "centroids") names(tabula) <- c("sp", "wa", "lc", "bp", "reg", "cn") if (is.null(x$CCA)) tabula <- tabula[1:2] display <- match.arg(display, c("sites", "species", "wa", "lc", "bp", "cn", "reg", "all"), several.ok = TRUE) ## set "all" for tidy scores if (tidy) display <- "all" if("sites" %in% display) display[display == "sites"] <- "wa" if("species" %in% display) display[display == "species"] <- "sp" if ("all" %in% display) display <- names(tabula) take <- tabula[display] sumev <- x$tot.chi ## dbrda can have negative eigenvalues, but have scores only for ## positive eigval <- eigenvals(x) if (inherits(x, "dbrda") && any(eigval < 0)) eigval <- eigval[eigval > 0] slam <- sqrt(eigval[choices]/sumev) nr <- if (is.null(x$CCA)) nrow(x$CA$u) else nrow(x$CCA$u) ## const multiplier of scores if (missing(const)) const <- sqrt(sqrt((nr-1) * sumev)) ## canoco 3 compatibility -- canoco 4 is incompatible ##else if (pmatch(const, "canoco")) { ## const <- (sqrt(nr-1), sqrt(nr)) ##} ## ## const[1] for species, const[2] for sites and friends if (length(const) == 1) { const <- c(const, const) } ## in dbrda we only have scores for positive eigenvalues if (inherits(x, "dbrda")) rnk <- x$CCA$poseig else rnk <- x$CCA$rank sol <- list() ## process scaling; numeric scaling will just be returned as is scaling <- scalingType(scaling = scaling, correlation = correlation) if ("species" %in% take) { v <- cbind(x$CCA$v, x$CA$v)[, choices, drop=FALSE] if (scaling) { scal <- list(1, slam, sqrt(slam))[[abs(scaling)]] v <- sweep(v, 2, scal, "*") if (scaling < 0) { v <- sweep(v, 1, x$colsum, "/") v <- v * sqrt(sumev / (nr - 1)) } v <- const[1] * v } if (nrow(v) > 0) sol$species <- v else sol$species <- NULL } if ("sites" %in% take) { wa <- cbind(x$CCA$wa, x$CA$u)[, choices, drop=FALSE] if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] wa <- sweep(wa, 2, scal, "*") wa <- const[2] * wa } sol$sites <- wa } if ("constraints" %in% take) { u <- cbind(x$CCA$u, x$CA$u)[, choices, drop=FALSE] if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] u <- sweep(u, 2, scal, "*") u <- const[2] * u } sol$constraints <- u } if ("biplot" %in% take && !is.null(x$CCA$biplot)) { b <- matrix(0, nrow(x$CCA$biplot), length(choices)) b[, choices <= rnk] <- x$CCA$biplot[, choices[choices <= rnk]] colnames(b) <- c(colnames(x$CCA$u), colnames(x$CA$u))[choices] rownames(b) <- rownames(x$CCA$biplot) if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] b <- sweep(b, 2, scal, "*") } sol$biplot <- b } if ("regression" %in% take) { b <- coef(x, norm = TRUE) reg <- matrix(0, nrow(b), length(choices)) reg[, choices <= rnk] <- b[, choices[choices <= rnk]] dimnames(reg) <- list(rownames(b), c(colnames(x$CCA$u), colnames(x$CA$u))[choices]) if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] reg <- sweep(reg, 2, scal, "*") } sol$regression <- reg } if ("centroids" %in% take) { if (is.null(x$CCA$centroids)) sol$centroids <- NULL else { cn <- matrix(0, nrow(x$CCA$centroids), length(choices)) cn[, choices <= rnk] <- x$CCA$centroids[, choices[choices <= rnk]] colnames(cn) <- c(colnames(x$CCA$u), colnames(x$CA$u))[choices] rownames(cn) <- rownames(x$CCA$centroids) if (scaling) { scal <- list(slam, 1, sqrt(slam))[[abs(scaling)]] cn <- sweep(cn, 2, scal, "*") cn <- const[2] * cn } sol$centroids <- cn } } ## Take care that scores have names if (length(sol)) { for (i in seq_along(sol)) { if (is.matrix(sol[[i]])) rownames(sol[[i]]) <- rownames(sol[[i]], do.NULL = FALSE, prefix = substr(names(sol)[i], 1, 3)) } } ## tidy scores if (tidy) { if (length(sol) == 0) # no scores return(NULL) ## re-group biplot arrays duplicating factor centroids if (!is.null(sol$biplot) && !is.null(sol$centroids)) { dup <- rownames(sol$biplot) %in% rownames(sol$centroids) if (any(dup)) { sol$factorbiplot <- sol$biplot[dup,, drop=FALSE] sol$biplot <- sol$biplot[!dup,, drop=FALSE] } } group <- sapply(sol, nrow) group <- rep(names(group), group) sol <- do.call(rbind, sol) label <- rownames(sol) sol <- as.data.frame(sol) sol$score <- as.factor(group) sol$label <- label } ## collapse const if both items identical if (identical(const[1], const[2])) const <- const[1] ## return NULL for list(), matrix for single scores, and a list ## for several scores sol <- switch(min(2, length(sol)), sol[[1]], sol) if (!is.null(sol)) attr(sol, "const") <- const sol }
/scratch/gouwar.j/cran-all/cranData/vegan/R/scores.rda.R
`screeplot.cca` <- function(x, bstick = FALSE, type = c("barplot", "lines"), npcs = min(10, if(is.null(x$CCA) || x$CCA$rank == 0) x$CA$rank else x$CCA$rank), ptype = "o", bst.col = "red", bst.lty = "solid", xlab = "Component", ylab = "Inertia", main = deparse(substitute(x)), legend = bstick, ...) { if(is.null(x$CCA) || x$CCA$rank == 0) eig.vals <- x$CA$eig else eig.vals <- x$CCA$eig ncomps <- length(eig.vals) if(npcs > ncomps) npcs <- ncomps comps <- seq(len=npcs) type <- match.arg(type) if (bstick && !is.null(x$CCA) && x$CCA$rank > 0) { warning("'bstick' unavailable for constrained ordination") bstick <- FALSE } if(bstick) { ord.bstick <- bstick(x) ylims <- range(eig.vals[comps], ord.bstick[comps]) } else { ylims <- range(eig.vals) } if(type=="barplot") { ## barplot looks weird if 0 not included ylims <- range(0, ylims) mids <- barplot(eig.vals[comps], names = names(eig.vals[comps]), main = main, ylab = ylab, ylim = ylims, ...) } else { plot(eig.vals[comps], type = ptype, axes = FALSE, ylim = ylims, xlab = xlab, ylab = ylab, main = main, ...) axis(2) axis(1, at = comps, labels = names(eig.vals[comps])) box() mids <- comps } if(bstick) { dot.args <- list(...) dot.nams <- names(dot.args) pch <- if("pch" %in% dot.nams) dot.args$pch else par("pch") lines(mids, ord.bstick[comps], type = ptype, col = bst.col, lty = bst.lty, pch = pch) if(legend) { col <- if("col" %in% dot.nams) dot.args$col else par("col") lty <- if("lty" %in% dot.nams) dot.args$lty else par("lty") if(type == "lines") { legend("topright", legend = c("Ordination","Broken Stick"), bty = "n", col = c(col, bst.col), lty = c(lty, bst.lty), pch = pch) } else { legend("topright", legend = "Broken Stick", bty = "n", col = bst.col, lty = bst.lty, pch = pch) } } } invisible(xy.coords(x = mids, y = eig.vals[comps])) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/screeplot.cca.R
`screeplot.decorana` <- function(x, bstick = FALSE, type = c("barplot", "lines"), npcs = 4, ptype = "o", bst.col = "red", bst.lty = "solid", xlab = "Component", ylab = "Inertia", main = deparse(substitute(x)), legend = bstick, ...) { eig.vals <- if (x$ira == 1) x$evals else x$evals.ortho comps <- seq(len=npcs) type <- match.arg(type) if (bstick) { ord.bstick <- bstick(x) ylims <- range(0, eig.vals[comps], ord.bstick[comps]) } else { ylims <- range(c(0, eig.vals)) } if(type=="barplot") { mids <- barplot(eig.vals[comps], names = names(eig.vals[comps]), main = main, ylab = ylab, ylim = ylims, ...) } else { plot(eig.vals[comps], type = ptype, axes = FALSE, xlab = xlab, ylab = ylab, main = main, ylim = ylims, ...) axis(2) axis(1, at = comps, labels = names(eig.vals[comps])) mids <- comps box() } if (bstick) { dot.args <- list(...) dot.nams <- names(dot.args) pch <- if ("pch" %in% dot.nams) dot.args$pch else par("pch") lines(mids, ord.bstick[comps], type = ptype, col = bst.col, lty = bst.lty, pch = pch) if (legend) { col <- if ("col" %in% dot.nams) dot.args$col else par("col") lty <- if ("lty" %in% dot.nams) dot.args$lty else par("lty") if (type == "lines") { legend("topright", legend = c("Ordination", "Broken Stick"), bty = "n", col = c(col, bst.col), lty = c(lty, bst.lty), pch = pch) } else { legend("topright", legend = "Broken Stick", bty = "n", col = bst.col, lty = bst.lty, pch = pch) } } } invisible(xy.coords(x = mids, y = eig.vals[comps])) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/screeplot.decorana.R
`screeplot.prcomp` <- function(x, bstick = FALSE, type = c("barplot", "lines"), npcs = min(10, length(x$sdev)), ptype = "o", bst.col = "red", bst.lty = "solid", xlab = "Component", ylab = "Inertia", main = deparse(substitute(x)), legend = bstick, ...) { type <- match.arg(type) eig.vals <- x$sdev^2 ## fix-up names on eig.vals names(eig.vals) <- dimnames(x$rotation)[[2]] ncomps <- length(eig.vals) if(npcs > ncomps) npcs <- ncomps comps <- seq(len=npcs) if(bstick) { ord.bstick <- bstick(x) ylims <- range(eig.vals[comps], ord.bstick[comps]) } else { ylims <- range(eig.vals) } if(type=="barplot") { ## barplot looks weird if 0 not included ylims <- range(0, ylims) mids <- barplot(eig.vals[comps], names = names(eig.vals[comps]), main = main, ylab = ylab, ylim = ylims, ...) } else { plot(comps, eig.vals[comps], type = ptype, axes = FALSE, main = main, xlab = xlab, ylab = ylab, ...) axis(2) axis(1, at = comps, labels = names(eig.vals[comps])) mids <- comps box() } if(bstick) { dot.args <- list(...) dot.nams <- names(dot.args) pch <- if("pch" %in% dot.nams) dot.args$pch else par("pch") lines(mids, ord.bstick[comps], type = ptype, col = bst.col, lty = bst.lty, pch = pch) if(legend) { col <- if("col" %in% dot.nams) dot.args$col else par("col") lty <- if("lty" %in% dot.nams) dot.args$lty else par("lty") if(type == "lines") { legend("topright", legend = c("Ordination","Broken Stick"), bty = "n", col = c(col, bst.col), lty = c(lty, bst.lty), pch = pch) } else { legend("topright", legend = "Broken Stick", bty = "n", col = bst.col, lty = bst.lty, pch = pch) } } } invisible(xy.coords(x = mids, y = eig.vals[comps])) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/screeplot.prcomp.R
`screeplot.princomp` <- function(x, bstick = FALSE, type = c("barplot", "lines"), npcs = min(10, length(x$sdev)), ptype = "o", bst.col = "red", bst.lty = "solid", xlab = "Component", ylab = "Inertia", main = deparse(substitute(x)), legend = bstick, ...) { type <- match.arg(type) eig.vals <- x$sdev^2 ncomps <- length(eig.vals) if(npcs > ncomps) npcs <- ncomps comps <- seq(len=npcs) if(bstick) { ord.bstick <- bstick(x) ylims <- range(eig.vals[comps], ord.bstick[comps]) } else { ylims <- range(eig.vals) } if(type=="barplot") { ## barplot looks weird if 0 not included ylims <- range(0, ylims) mids <- barplot(eig.vals[comps], names = names(eig.vals[comps]), main = main, ylab = ylab, ylim = ylims, ...) } else { plot(comps, eig.vals[comps], type = ptype, axes = FALSE, main = main, xlab = xlab, ylab = ylab, ...) axis(2) axis(1, at = comps, labels = names(eig.vals[comps])) mids <- comps box() } if(bstick) { dot.args <- list(...) dot.nams <- names(dot.args) pch <- if("pch" %in% dot.nams) dot.args$pch else par("pch") lines(mids, ord.bstick[comps], type = ptype, col = bst.col, lty = bst.lty, pch = pch) if(legend) { col <- if("col" %in% dot.nams) dot.args$col else par("col") lty <- if("lty" %in% dot.nams) dot.args$lty else par("lty") if(type == "lines") { legend("topright", legend = c("Ordination","Broken Stick"), bty = "n", col = c(col, bst.col), lty = c(lty, bst.lty), pch = pch) } else { legend("topright", legend = "Broken Stick", bty = "n", col = bst.col, lty = bst.lty, pch = pch) } } } invisible(xy.coords(x = mids, y = eig.vals[comps])) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/screeplot.princomp.R
`showvarparts` <- function(parts, labels, bg = NULL, alpha=63, Xnames, id.size=1.2, ...) { rad <- 0.725 ## Default names if (missing(Xnames)) Xnames <- paste("X", seq_len(parts), sep="") ## transparent fill colours if (!is.null(bg)) { bg <- rgb(t(col2rgb(bg)), alpha = alpha, maxColorValue = 255) if (length(bg) < parts) bg <- rep(bg, length.out = parts) } ## centroids of circles (parts < 4) or individual fractions (parts ## == 4) cp <- switch(parts, matrix(c(0,0), ncol=2, byrow=TRUE), matrix(c(0,0, 1,0), ncol=2, byrow=TRUE), matrix(c(0,0, 1,0, 0.5, -sqrt(3/4)), ncol=2, byrow=TRUE), structure( c(-1.2, -0.6, 0.6, 1.2, -0.7, 0, -0.7, 0, 0.7, 0.7, 0.3, -0.4, 0.4, -0.3, 0, 0, 0.7, 0.7, 0, 0.3, 0.4, -0.6,-1.2, -0.6, 0.3, -0.7, 0, 0, -0.7, -0.4), .Dim = c(15L, 2L)) ) ## plot limits if (parts < 4) { xlim <- range(cp[,1]) + c(-rad, rad) ylim <- range(cp[,2]) + c(-rad, rad) } else { xlim <- c(-1.7, 1.7) ylim <- c(-1.7, 1.1) } ## plot plot(cp, axes=FALSE, xlab="", ylab="", asp=1, type="n", xlim = xlim, ylim = ylim) box() if (parts < 4) { symbols(cp, circles = rep(rad, min(parts,3)), inches = FALSE, add=TRUE, bg = bg, ...) ## Explanatory data set names added by PL if(parts==2) { pos.names = matrix(c(-0.65,1.65,0.65,0.65),2,2) } else if(parts==3) { pos.names = matrix(c(-0.65,1.65,-0.16,0.65,0.65,-1.5),3,2) } text(pos.names,labels=Xnames[1:parts], cex=id.size) } else { ## Draw ellipses with veganCovEllipse. Supply 2x2 ## matrix(c(d,a,a,d), 2, 2) which defines an ellipse of ## semi-major axis length sqrt(d+a) semi-minor axis sqrt(d-a). d <- 1 a <- 1/sqrt(2) ## Small ellipses X2, X3 at the centroid e2 <- veganCovEllipse(matrix(c(d,-a,-a,d), 2, 2)) e3 <- veganCovEllipse(matrix(c(d, a, a,d), 2, 2)) ## wider ellipses X1, X4 at sides going through the centroid L <- d+a W <- (sqrt(L) - sqrt(d-a))^2 d <- (L+W)/2 a <- (L-W)/2 cnt <- sqrt(W/2) e1 <- veganCovEllipse(matrix(c(d,-a,-a,d), 2, 2), c(-cnt, -cnt)) e4 <- veganCovEllipse(matrix(c(d, a, a,d), 2, 2), c( cnt, -cnt)) polygon(rbind(e1,NA,e2,NA,e3,NA,e4), col = bg, ...) ## Explanatory data set names added by PL pos.names = matrix(c(-1.62,-1.10,1.10,1.62,0.54,1.00,1.00,0.54),4,2) text(pos.names,labels=Xnames[1:4], cex=id.size) } ## label fractions nlabs <- switch(parts, 2, 4, 8, 16) if (missing(labels)) labels <- paste("[", letters[1:nlabs], "]", sep="") if (length(labels) != nlabs) stop(gettextf("needs %d labels, but input has %d", nlabs, length(labels))) switch(parts, text(0,0, labels[-nlabs], ...), text(rbind(cp, colMeans(cp)), labels[-nlabs], ...), text(rbind(cp, colMeans(cp[1:2,]), colMeans(cp[2:3,]), colMeans(cp[c(1,3),]), colMeans(cp)), labels[-nlabs], ...), text(cp, labels[-nlabs], ...) ) xy <- par("usr") text(xy[2] - 0.05*diff(xy[1:2]), xy[3] + 0.05*diff(xy[3:4]), paste("Residuals =", labels[nlabs]), pos = 2, ...) invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/showvarparts.R
### SIMPER: contributions of species on overall dissimilarity with ### emphasis on among-group dissimilarities. Generate full ### dissimilarity matrix first and then subsample. `simper` <- function(comm, group, permutations = 999, parallel = 1, ...) { ## parallel processing not yet implemented if (!missing(parallel)) .NotYetUsed("parallel", error = FALSE) EPS <- sqrt(.Machine$double.eps) comm <- as.matrix(comm) ## take lower triangle without as.dist overhead tri <- outer(seq_len(nrow(comm)), seq_len(nrow(comm)), ">") ## Species contributions of differences needed for every species, ## but denominator is constant. Bray-Curtis is actually ## manhattan/(mean(rowsums)) and this is the way we collect data rs <- rowSums(comm) rs <- outer(rs, rs, "+")[tri] spcontr <- sapply(seq_len(ncol(comm)), function(i) as.vector(vegdist(comm[, i, drop = FALSE], "man"))) ## Bray-Curtis spcontr <- sweep(spcontr, 1, rs, "/") colnames(spcontr) <- colnames(comm) outlist <- NULL ## Averages of species contributions ## Case 1: overall differences without grouping if (missing(group) || length(unique(group)) == 1) { nperm <- 0 permat <- NULL average <- colMeans(spcontr) overall <- sum(average) sdi <- apply(spcontr, 2, sd) ord <- order(average, decreasing = TRUE) cusum <- cumsum(average[ord])/overall outlist[["total"]] <- list(species = colnames(comm), average = average, overall = overall, sd = sdi, ratio = average/sdi, ava = NULL, avb = NULL, ord = ord, cusum = cusum, p = NULL) } else { ## Case 2: two or more groups comp <- t(combn(as.character(unique(group)), 2)) ## data averages by group (do we need these?) spavg <- apply(comm, 2, function(x) tapply(x, group, mean)) ## function to match constrasts contrmatch <- function(X, Y, patt) X != Y & X %in% patt & Y %in% patt for (i in seq_len(nrow(comp))) { tmat <- outer(group, group, FUN=contrmatch, patt=comp[i,]) take <- tmat[tri] average <- colMeans(spcontr[take,,drop=FALSE]) overall <- sum(average) sdi <- apply(spcontr[take,,drop=FALSE], 2, sd) ratio <- average/sdi ord <- order(average, decreasing = TRUE) cusum <- cumsum(average[ord])/overall ava <- spavg[comp[i,1],] avb <- spavg[comp[i,2],] ## Permutation tests for average permat <- getPermuteMatrix(permutations, nrow(comm)) nperm <- nrow(permat) if (nperm) { Pval <- rep(1, ncol(comm)) for (k in seq_len(nperm)) { take <- tmat[permat[k,],permat[k,]][tri] Pval <- Pval + ((colMeans(spcontr[take,]) - EPS) >= average) } Pval <- Pval/(nperm+1) } else { Pval <- NULL } ## output outlist[[paste(comp[i,], collapse="_")]] <- list(species = colnames(comm), average = average, overall = overall, sd = sdi, ratio = ratio, ava = ava, avb = avb, ord = ord, cusum = cusum, p = Pval) } } class(outlist) <- "simper" attr(outlist, "permutations") <- nperm attr(outlist, "control") <- attr(permat, "control") outlist } `print.simper` <- function(x, ...) { cat("cumulative contributions of most influential species:\n\n") cusum <- lapply(x, function(z) z$cusum) spec <- lapply(x, function(z) z$species[z$ord]) for (i in seq_along(cusum)) { names(cusum[[i]]) <- spec[[i]] } ## this probably fails with empty or identical groups that have 0/0 = NaN out <- lapply(cusum, function(z) z[seq_len(min(which(z >= 0.7)))]) print(out) invisible(x) } `summary.simper` <- function(object, ordered = TRUE, digits = max(3, getOption("digits") - 3), ...) { if (ordered) { out <- lapply(object, function(z) data.frame(cbind(average = z$average, sd = z$sd, ratio = z$ratio, ava = z$ava, avb = z$avb)[z$ord, ])) cusum <- lapply(object, function(z) z$cusum) for(i in seq_along(out)) { out[[i]]$cumsum <- cusum[[i]] if(!is.null(object[[i]]$p)) { out[[i]]$p <- object[[i]]$p[object[[i]]$ord] } } } else { out <- lapply(object, function(z) data.frame(cbind(average = z$average, sd = z$sd, ratio = z$ratio, ava = z$ava, avb = z$avb, p = z$p))) } attr(out, "digits") <- digits attr(out, "permutations") <- attr(object, "permutations") attr(out, "control") <- attr(object, "control") class(out) <- "summary.simper" out } `print.summary.simper`<- function(x, digits = attr(x, "digits"), ...) { for (nm in names(x)) { cat("\nContrast:", nm, "\n\n") printCoefmat(x[[nm]], digits = digits, has.Pvalue = TRUE, zap.ind = seq_len(ncol(x[[nm]])), ...) } if (!is.null(attr(x, "control"))) cat(howHead(attr(x, "control"))) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/simper.R
### An internal function used in varpart(): Returns only the raw ### Rsquare and the rank of constraints in RDA. `simpleRDA2` <- function (Y, X, SS.Y, ...) { Q <- qr(X, tol=1e-6) Yfit.X <- qr.fitted(Q, Y) SS <- sum(Yfit.X^2) if (missing(SS.Y)) SS.Y <- sum(Y^2) Rsquare <- SS/SS.Y R2adj <- RsquareAdj(Rsquare, nrow(Y), Q$rank) list(Rsquare = Rsquare, RsquareAdj = R2adj, m = Q$rank) } ### Analogous function, but the input must be Gower double-centred ### dissimilarities 'G = -GowerDblcen(as.matrix(dist(Y)^2))/2'. The ### math is based on McArdle & Anderson, Ecology 82: 290-297 (2001). `simpleDBRDA` <- function(G, X, SS.G, ...) { Q <- qr(X, tol=1e-6) Yfit.X <- qr.fitted(Q, G) SS <- sum(diag(Yfit.X)) if (missing(SS.G)) SS.G <- sum(diag(G)) Rsquare <- SS/SS.G R2adj <- RsquareAdj(Rsquare, nrow(G), Q$rank) list(Rsquare = Rsquare, RsquareAdj = R2adj, m = Q$rank) } ### Analogous function for CCA. We initialize data with weighted ### double standaradization, and centre constraints X by row ### weights. The approximation of weighted R-square is found via ### permutations in permat (which must be given). `simpleCCA` <- function(Y, X, SS.Y, permat, ...) { Y <- initCA(Y) if(missing(SS.Y)) SS.Y <- sum(Y^2) w <- attr(Y, "RW") X <- .Call(do_wcentre, X, w) Q <- qr(X, tol=1e-6) Yfit.X <- qr.fitted(Q, Y) SS <- sum(Yfit.X^2) Rsquare <- SS/SS.Y ## permutation to estimate adjusted R2 meanSS <- mean(sapply(seq_len(nrow(permat)), function(i) sum(qr.fitted(Q, Y[permat[i,],])^2))) R2adj <- 1 - ((1 - Rsquare) / (1 - meanSS/SS.Y)) list(Rsquare = Rsquare, RsquareAdj = R2adj, m = Q$rank) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/simpleRDA2.R
### unbiased Simpson index, Hurlbert (1971) "nonconcept" paper, eq. 5, ### but implemented here with rarefy (because I'm lazy and just re-use ### work already done). `simpson.unb` <- function(x, inverse = FALSE) { d <- rarefy(x, 2) - 1 ## alternatively use directly the Hurlbert equation ## n <- rowSums(x) ## d <- rowSums(x/n*(n-x)/(n-1)) if (inverse) d <- 1/(1-d) attr(d, "Subsample") <- NULL d }
/scratch/gouwar.j/cran-all/cranData/vegan/R/simpson.unb.R
simulate.nullmodel <- function(object, nsim=1, seed = NULL, burnin=0, thin=1, ...) { if (!exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) runif(1) if (is.null(seed)) RNGstate <- get(".Random.seed", envir = .GlobalEnv) else { R.seed <- get(".Random.seed", envir = .GlobalEnv) set.seed(seed) RNGstate <- structure(seed, kind = as.list(RNGkind())) on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv)) } if (nsim < 1) stop("'nsim' must be at least 1") m <- object$data if (object$commsim$isSeq) { ## here is burnin, see update method if (burnin > 0) object <- update(object, burnin, ...) x <- object$state } else { x <- m ## non-sequential models have no burnin -- but they may have ## thinning: set burnin=0, but leave thin like user set it. burnin <- 0L } perm <- object$commsim$fun(x=x, n=as.integer(nsim), nr=object$nrow, nc=object$ncol, rs=object$rowSums, cs=object$colSums, rf=object$rowFreq, cf=object$colFreq, s=object$totalSum, fill=object$fill, thin=as.integer(thin), ...) if (object$commsim$isSeq) { Start <- object$iter + thin End <- object$iter + nsim * thin ## sequence can overflow integer if (Start <= .Machine$integer.max) Start <- as.integer(Start) if (End <= .Machine$integer.max) End <- as.integer(End) state <- perm[,,nsim] storage.mode(state) <- object$commsim$mode assign("state", state, envir=object) assign("iter", End, envir=object) } else { Start <- 1L End <- as.integer(nsim) } attr(perm, "data") <- m attr(perm, "seed") <- RNGstate attr(perm, "method") <- object$commsim$method attr(perm, "binary") <- object$commsim$binary attr(perm, "isSeq") <- object$commsim$isSeq attr(perm, "mode") <- object$commsim$mode attr(perm, "start") <- Start attr(perm, "end") <- End attr(perm, "thin") <- as.integer(thin) class(perm) <- c("simmat", "array") dimnames(perm) <- list(rownames(m), colnames(m), paste("sim", seq_len(nsim), sep = "_")) perm }
/scratch/gouwar.j/cran-all/cranData/vegan/R/simulate.nullmodel.R
`simulate.rda` <- function(object, nsim = 1, seed = NULL, indx = NULL, rank = "full", correlated = FALSE, ...) { ## Fail if there is no constrained component (it could be possible ## to change the function to handle unconstrained ordination, too, ## when rank < "full", but that would require redesign) if (is.null(object$CCA)) stop("function can be used only with constrained ordination") ## Handle RNG: code directly from stats::simulate.lm if (!exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) runif(1) if (is.null(seed)) RNGstate <- get(".Random.seed", envir = .GlobalEnv) else { R.seed <- get(".Random.seed", envir = .GlobalEnv) set.seed(seed) RNGstate <- structure(seed, kind = as.list(RNGkind())) on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv)) } ## indx can be an output of permute::shuffleSet in which case it ## is a nsim x nrow matrix, or it may be a single vector, in which ## case it will changed to shuffleSet if (!is.null(indx)) if (is.vector(indx)) dim(indx) <- c(1, length(indx)) ## If nsim is missing, take it from indx (if given) if (missing(nsim) && !is.null(indx)) nsim <- nrow(indx) ## Check that dims match if (!is.null(indx)) if(nrow(indx) != nsim) stop(gettextf("'nsim' (%d) and no. of 'indx' rows (%d) do not match", nsim, nrow(indx))) ## collect data to back-transform data to the scale of observations sqnr1 <- sqrt(nobs(object) - 1) ## the ifs are only needed to cope with pre-2.5-0 vegan: now ## we always have Ybar, but earlier we needed to check whether ## we had CA or CCA Xbar if (!is.null(object$Ybar)) { cnt <- attr(object$Ybar, "scaled:center") scl <- attr(object$Ybar, "scaled:scale") } else { # needed for vegan-2.4 compatibility if (is.null(object$CCA)) tmp <- object$CA$Xbar else tmp <- object$CCA$Xbar cnt <- attr(tmp, "scaled:center") scl <- attr(tmp, "scaled:scale") } ## Proper simulation: very similar for simulate.lm, but produces ## an array of response matrices ftd <- predict(object, type = "working", rank = rank) ## pRDA: add partial Fit to the constrained if (!is.null(object$pCCA)) ftd <- ftd + ordiYbar(object, "pCCA") ## if(is.null(indx)), we have parametric Gaussian simulation and ## need to generate sd matrices. The residuals sd is always taken ## from the unconstrained (residual) component. If ## species are uncorrelated, we need only species sd's, but if ## correlated, we also need species covariances. CAYbar <- ordiYbar(object, "CA") if (!correlated) dev <- outer(rep(1, nrow(ftd)), apply(CAYbar, 2, sd)) else dev <- cov(CAYbar) ## Generate an array ans <- array(0, c(dim(ftd), nsim)) for (i in seq_len(nsim)) { if (!is.null(indx)) ans[,,i] <- as.matrix(ftd + CAYbar[indx[i,],]) else if (!correlated) ans[,,i] <- as.matrix(ftd + matrix(rnorm(length(ftd), sd = dev), nrow = nrow(ftd))) else { ans[,,i] <- t(apply(ftd, 1, function(x) mvrnorm(1, mu = x, Sigma = dev))) } ## ans to the scale of observations ans[,,i] <- ans[,,i] * sqnr1 if (!is.null(scl)) ans[,,i] <- sweep(ans[,,i], 2, scl, "*") ans[,,i] <- sweep(ans[,,i], 2, cnt, "+") } ## set RNG attributes if (is.null(indx)) attr(ans, "seed") <- RNGstate else attr(ans, "seed") <- "index" ## set commsim attributes if nsim > 1, else return a 2-dim matrix if (nsim == 1) { ans <- ans[,,1] attributes(ans) <- attributes(ftd) } else { dimnames(ans) <- list(rownames(ftd), colnames(ftd), paste("sim", seq_len(nsim), sep = "_")) orig <- (ftd + CAYbar) * sqnr1 if (!is.null(scl)) orig <- sweep(orig, 2, scl, "*") orig <- sweep(orig, 2, cnt, "+") attr(ans, "data") <- round(orig, 12) attr(ans, "method") <- paste("simulate", ifelse(is.null(indx), "parametric", "index")) attr(ans, "binary") <- FALSE attr(ans, "isSeq") <- FALSE attr(ans, "mode") <- "double" attr(ans, "start") <- 1L attr(ans, "end") <- as.integer(nsim) attr(ans, "thin") <- 1L class(ans) <- c("simulate.rda", "simmat", "array") } ans } ### simulate. cca was cloned from simulate.rda. Works with internal ### Chi-square standardized form, and at the end back-standardizes ### with row and column totals and matrix grand totals. This does not ### still guarantee that all marginal totals are positive. `simulate.cca` <- function(object, nsim = 1, seed = NULL, indx = NULL, rank = "full", correlated = FALSE, ...) { ## Fail if no CCA if (is.null(object$CCA)) stop("function can be used only with constrained ordination") ## Handle RNG: code directly from stats::simulate.lm if (!exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) runif(1) if (is.null(seed)) RNGstate <- get(".Random.seed", envir = .GlobalEnv) else { R.seed <- get(".Random.seed", envir = .GlobalEnv) set.seed(seed) RNGstate <- structure(seed, kind = as.list(RNGkind())) on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv)) } ## Preparations like in simulate.rda() if (!is.null(indx)) if (is.vector(indx)) dim(indx) <- c(1, length(indx)) if (missing(nsim) && !is.null(indx)) nsim <- nrow(indx) if (!is.null(indx)) if(nrow(indx) != nsim) stop(gettextf("'nsim' (%d) and no. of 'indx' rows (%d) do not match", nsim, nrow(indx))) ## Need sqrt of rowsums for weighting sq.r <- sqrt(object$rowsum) ## Fitted value ftd <- predict(object, type = "working", rank = rank) ## pCCA: add partial Fit to the constrained if (!is.null(object$pCCA)) ftd <- ftd + ordiYbar(object, "pCCA") ## Residual Xbar need weighting and back-weighting Xbar <- sweep(ordiYbar(object, "CA"), 1, sq.r, "*") ## Simulation if (correlated) dev <- cov(Xbar) else dev <- outer(rep(1, nrow(ftd)), apply(Xbar, 2, sd)) ans <- array(0, c(dim(ftd), nsim)) for (i in seq_len(nsim)) { if (is.null(indx)) { if (correlated) tmp <- mvrnorm(nrow(ftd), numeric(ncol(ftd)), Sigma = dev) else tmp <- matrix(rnorm(length(ftd), sd = dev), nrow = nrow(ftd)) ans[,,i] <- as.matrix(ftd + sweep(tmp, 1, sq.r, "/")) } else ans[,,i] <- as.matrix(ftd + sweep(Xbar[indx[i,],], 1, sq.r, "/")) } ## From internal form to the original form with fixed marginal totals rc <- object$rowsum %o% object$colsum for (i in seq_len(nsim)) ans[,,i] <- (ans[,,i] * sqrt(rc) + rc) * object$grand.total ## RNG attributes if (is.null(indx)) attr(ans, "seed") <- RNGstate else attr(ans, "seed") <- "index" ## set commsim attributes if nsim > 1, else return a 2-dim matrix if (nsim == 1) { ans <- ans[,,1] attributes(ans) <- attributes(ftd) } else { dimnames(ans) <- list(rownames(ftd), colnames(ftd), paste("sim", seq_len(nsim), sep = "_")) obsdata <- ordiYbar(object, "initial") obsdata <- (obsdata * sqrt(rc) + rc) * object$grand.total attr(ans, "data") <- round(obsdata, 12) attr(ans, "method") <- paste("simulate", ifelse(is.null(indx), "parametric", "index")) attr(ans, "binary") <- FALSE attr(ans, "isSeq") <- FALSE attr(ans, "mode") <- "double" attr(ans, "start") <- 1L attr(ans, "end") <- as.integer(nsim) attr(ans, "thin") <- 1L class(ans) <- c("simulate.cca", "simmat", "array") } ans } ### capscale method: copies simulate.rda as much as possible. Function ### works with the internal metric scaling mapping of fit and error, ### but returns Euclidean distances adjusted to the original scaling ### of input dissimilarities. Only the real components are used, and ### capscale() of simulated dissimilarities have no Imaginary ### component. `simulate.capscale` <- function(object, nsim = 1, seed = NULL, indx = NULL, rank = "full", correlated = FALSE, ...) { ## Fail if no CCA component if (is.null(object$CCA)) stop("function can be used only with constrained ordination") if (is.null(indx) && correlated) warning("argument 'correlated' does not work and will be ignored") ## Handle RNG: code directly from stats::simulate.lm if (!exists(".Random.seed", envir = .GlobalEnv, inherits = FALSE)) runif(1) if (is.null(seed)) RNGstate <- get(".Random.seed", envir = .GlobalEnv) else { R.seed <- get(".Random.seed", envir = .GlobalEnv) set.seed(seed) RNGstate <- structure(seed, kind = as.list(RNGkind())) on.exit(assign(".Random.seed", R.seed, envir = .GlobalEnv)) } if (nsim > 1) .NotYetUsed("nsim") ## predict.capscale cannot be used because it returns either ## dissimilarities ("response") or scores with the rank of the ## constrained solution, and we need rank of the data (not of ## constraints). if (rank > 0) { ftd <- ordiYbar(object, "CCA") ## redo analysis when rank < full if (rank < object$CCA$rank) { x <- svd(ftd, nu = rank, nv = rank) ftd <- x$u %*% diag(x$d[1:rank], nrow=rank) %*% t(x$v) } } else { ftd <- 0 } ## add partial Fit to the constrained if (!is.null(object$pCCA)) ftd <- ftd + ordiYbar(object, "pCCA") if (is.null(indx)) ans <- as.data.frame(ftd + matrix(rnorm(length(ftd), sd = outer(rep(1,nrow(ftd)), apply(ordiYbar(object, "CA"), 2, sd))), nrow = nrow(ftd))) else ans <- ftd + ordiYbar(object, "CA")[indx,] ## return Euclidean distances ans <- ans * object$adjust ans <- dist(ans) ## remove adjustment done in capscale and put dissimilarities to ## (approximately) original scale if (is.null(indx)) attr(ans, "seed") <- RNGstate else attr(ans, "seed") <- indx ans } ### simulate.dbrda cannot be done along similar lines as ### simulate.capscale, because low-rank approximation needs column ### scores v and cannot be found only from row scores u that are the ### only ones we have in dbrda(). Residuals also need exra thinking, ### and therefore we just disable simulate.dbrda() `simulate.dbrda` <- function(object, nsim = 1, seed = NULL, ...) { .NotYetImplemented() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/simulate.rda.R
`smbind` <- function (object, ..., MARGIN, strict = TRUE) { if (missing(MARGIN)) stop("MARGIN argument must be specified") MARGIN <- as.integer(MARGIN) if (length(MARGIN) != 1L) stop("MARGIN length must be 1") if (!(MARGIN %in% 1L:3L)) stop("MARGIN value must be in 1:3") if (is.list(object)) { obj <- object if (!missing(...)) warning("'object' was a list, '...' ignored") } else { obj <- list(object, ...) } l <- length(obj) if (l < 2L) return(obj[[1L]]) att <- lapply(obj, attributes) isSeq <- att[[1L]]$isSeq startEq <- endEq <- thinEq <- OKseed <- TRUE for (i in 2L:l) { ## data must be identical when MARGIN=3 if (MARGIN == 3L && !identical(att[[1L]][["data"]], att[[i]][["data"]])) stop("'data' attributes are not identical") ## dimensions need to match except for MARGIN if (!identical(att[[1L]][["dim"]][-MARGIN], att[[i]][["dim"]][-MARGIN])) stop("dimension mismatch") ## method settings need to be set on return object ## thus these need to be identical for (NAM in c("method", "binary", "isSeq", "mode", "class")) { if (!identical(att[[1L]][[NAM]], att[[i]][[NAM]])) stop(gettextf("'%s' attributes not identical", NAM)) } ## ts attributes are tricky: evaluate outside of the loop for (NAM in c("start", "end", "thin")) { if (!identical(att[[1L]][["start"]], att[[i]][["start"]])) startEq <- FALSE if (!identical(att[[1L]][["end"]], att[[i]][["end"]])) endEq <- FALSE if (!identical(att[[1L]][["thin"]], att[[i]][["thin"]])) thinEq <- FALSE } ## seed is important when 'data' are the same (MARGIN=3) ## but it is up to the user ## return value has NULL seed attribute if (MARGIN == 3L && identical(att[[1L]][["seed"]], att[[i]][["seed"]])) { OKseed <- FALSE } } if (!OKseed) warning("identical 'seed' attributes found") if (isSeq) { outStart <- outEnd <- outThin <- NA type <- "none" ## if MARGIN != 3 ## all match or fail ## when all match: keep ts attributes, type: "strat" ## if MARGIN==3 ## sequential algorithms need identical ts attributes ## * if parallel (start/end/thin identical): "par" ## --> original start, end, thin, + set chains attr ## * if subsequent (start/end/thin form a sequence): "seq" ## --> calculate start & end, thin same ## * all else: "none" ## --> fail unless strict=FALSE (when start=NA, end=NA, thin=NA) if (MARGIN != 3L) { if (startEq && endEq && thinEq) { type <- "strat" outStart <- att[[1L]]$start outEnd <- att[[1L]]$end outThin <- att[[1L]]$thin } } else { if (startEq && endEq && thinEq) { type <- "par" outStart <- att[[1L]]$start outEnd <- att[[1L]]$end outThin <- att[[1L]]$thin } if (!startEq && !endEq && thinEq) { stv <- sapply(att, "[[", "start") o <- order(stv) att <- att[o] obj <- obj[o] stv <- sapply(att, "[[", "start") env <- sapply(att, "[[", "end") thv <- att[[1L]]$thin nsv <- sapply(obj, function(z) dim(z)[3L]) vals <- lapply(1:l, function(i) seq(stv[i], env[i], by=thv)) OK <- logical(4L) if (length(stv) == length(unique(stv))) OK[1L] <- TRUE if (length(env) == length(unique(env))) OK[2L] <- TRUE if (all(nsv == sapply(vals, length))) OK[3L] <- TRUE if (length(seq(stv[1], env[l], by=thv)) == length(unlist(vals))) OK[4L] <- TRUE if (all(OK)) { if (all(seq(stv[1], env[l], by=thv) == unlist(vals))) { type <- "seq" outStart <- stv[1] outEnd <- env[l] outThin <- thv } } } } if (type == "none") { if (strict) { stop("incosistent 'start', 'end', 'thin' attributes") } else { warning("incosistent 'start', 'end', 'thin' attributes") } } } ## set final dimensions DIM <- att[[1L]]$dim DIMs <- sapply(att, function(z) z$dim[MARGIN]) cDIMs <- cumsum(DIMs) DIM[MARGIN] <- cDIMs[l] out <- array(NA, dim = DIM) ## copy the 1st object if (MARGIN == 1L) out[1L:dim(obj[[1L]])[1L],,] <- obj[[1L]] if (MARGIN == 2L) out[,1L:dim(obj[[1L]])[2L],] <- obj[[1L]] if (MARGIN == 3L) out[,,1L:dim(obj[[1L]])[3L]] <- obj[[1L]] ## data attribute will change when MARGIN != 3 DATA <- att[[1L]]$data ## copy 2:l objects and data argument for (i in 2L:l) { j <- (cDIMs[i - 1L] + 1L):cDIMs[i] if (MARGIN == 1L) { out[j,,] <- obj[[i]] DATA <- rbind(DATA, att[[i]]$data) } if (MARGIN == 2L) { out[,j,] <- obj[[i]] DATA <- cbind(DATA, att[[i]]$data) } if (MARGIN == 3L) { out[,,j] <- obj[[i]] } } ## assembling return object ratt <- att[[1L]] ratt$data <- DATA ratt$seed <- NA ratt$dim <- DIM if (!isSeq) ratt$end <- cDIMs[l] if (isSeq) { ratt$start <- outStart ratt$end <- outEnd ratt$thin <- outThin if (type == "par") ratt$chains <- l } ratt$dimnames[[MARGIN]] <- make.names(unlist(lapply(att, function(z) z$dimnames[[MARGIN]])), unique = TRUE) attributes(out) <- ratt out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/smbind.R
### The depths of nodes in a 'spantree' object: The nodes are either ### leaves with one link, or internal nodes with >1 links. The leaves ### are removed recursively from the tree and at each step the depth ### is increased with one. `spandepth` <- function (x) { if (!inherits(x, "spantree")) stop("'x' must be 'spantree' result") kid <- c(NA, x$kid) par <- p <- seq_along(kid) par[1] <- NA ## Isolated nodes in disconnected tree have depth 0, other nodes ## start from depth 1 intree <- p %in% kid | !is.na(kid) depth <- numeric(length(par)) depth[intree] <- 1 if (!is.null(x$labels)) names(depth) <- x$labels while(any(intree)) { ## Node is internal (intree) if it is both a parent and a kid ## and kid is in the tree or it is kid to two or more parents intree <- (p %in% intersect(kid[intree], par[intree]) & p %in% p[intree][kid[intree] %in% p[intree]] | p %in% kid[intree][duplicated(kid[intree])]) depth[intree] <- depth[intree] + 1 } depth }
/scratch/gouwar.j/cran-all/cranData/vegan/R/spandepth.R
`spantree` <- function (d, toolong = 0) { if (!inherits(d, "dist")) { if ((is.matrix(d) || is.data.frame(d)) && isSymmetric(unname(as.matrix(d)))) { d <- as.dist(d) } else { stop("input must be dissimilarities") } } if (!is.numeric(d)) stop("input data must be numeric") n <- attr(d, "Size") labels <- labels(d) dis <- .C(primtree, dist = as.double(d), toolong = as.double(toolong), n = as.integer(n), val = double(n + 1), dad = integer(n + 1), NAOK = TRUE) out <- list(kid = dis$dad[2:n] + 1, dist = dis$val[2:n], labels = labels, n = n, call = match.call()) class(out) <- "spantree" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/spantree.R
`specaccum` <- function (comm, method = "exact", permutations = 100, conditioned=TRUE, gamma="jack1", w = NULL, subset, ...) { METHODS <- c("collector", "random", "exact", "rarefaction", "coleman") method <- match.arg(method, METHODS) if (!is.null(w) && !(method %in% c("random", "collector"))) stop("weights 'w' can be only used with methods 'random' and 'collector'") if (!missing(subset)) { comm <- subset(comm, subset) w <- subset(w, subset) } x <- comm x <- as.matrix(x) x <- x[, colSums(x) > 0, drop=FALSE] n <- nrow(x) p <- ncol(x) accumulator <- function(x, ind) { rowSums(apply(x[ind, , drop=FALSE], 2, cumsum) > 0) } specaccum <- sdaccum <- sites <- perm <- NULL if (n == 1 && method != "rarefaction") message("no actual accumulation since only one site provided") switch(method, collector = { sites <- seq_len(n) xout <- weights <- cumsum(w) specaccum <- accumulator(x, sites) perm <- as.matrix(specaccum) weights <- as.matrix(weights) }, random = { permat <- getPermuteMatrix(permutations, n) perm <- apply(permat, 1, accumulator, x = x) if (!is.null(w)) weights <- as.matrix(apply(permat, 1, function(i) cumsum(w[i]))) sites <- seq_len(n) if (is.null(w)) { specaccum <- apply(perm, 1, mean) sdaccum <- apply(perm, 1, sd) } else { sumw <- sum(w) xout <- seq(sumw/n, sumw, length.out = n) intx <- sapply(seq_len(NCOL(perm)), function(i) approx(weights[,i], perm[,i], xout = xout)$y) specaccum <- apply(intx, 1, mean) sdaccum <- apply(intx, 1, sd) } }, exact = { freq <- colSums(x > 0) freq <- freq[freq > 0] f <- length(freq) ldiv <- lchoose(n, 1:n) result <- array(dim = c(n, f)) for (i in 1:n) { result[i, ] <- ifelse(n - freq < i, 0, exp(lchoose(n - freq, i) - ldiv[i])) } sites <- 1:n specaccum <- rowSums(1 - result) if (conditioned) { V <- result * (1 - result) tmp1 <- cor(x > 0) ind <- lower.tri(tmp1) tmp1 <- tmp1[ind] tmp1[is.na(tmp1)] <- 0 cv <- numeric(n) for (i in 1:n) { tmp2 <- outer(sqrt(V[i, ]), sqrt(V[i, ]))[ind] cv[i] <- 2 * sum(tmp1 * tmp2) } V <- rowSums(V) sdaccum <- sqrt(V + cv) }else{ Stot <- specpool(x)[,gamma] sdaccum1 <- rowSums((1-result)^2) sdaccum2 <- specaccum^2/Stot sdaccum <- sqrt(sdaccum1 - sdaccum2) } }, rarefaction = { ## rarefaction should be done on observed counts that usually ## have singletons. Warn here but not on every row when ## calling rarefy(). minobs <- min(x[x > 0]) if (minobs > 1) warning( gettextf("most observed count data have counts 1, but smallest count is %d", minobs)) freq <- colSums(x) freq <- freq[freq > 0] tot <- sum(freq) ind <- round(seq(tot/n, tot, length = n)) result <- matrix(NA, nrow = 2, ncol = n) for (i in 1:n) { result[, i] <- suppressWarnings(rarefy(t(freq), ind[i], se = TRUE)) } specaccum <- result[1, ] sdaccum <- result[2, ] sites <- ind/tot * n }, coleman = { freq <- colSums(x > 0) result <- array(dim = c(n, p)) for (i in 1:n) { result[i, ] <- (1 - i/n)^freq } result <- 1 - result sites <- seq_len(n) specaccum <- rowSums(result) sdaccum <- sqrt(rowSums(result * (1 - result))) }) out <- list(call = match.call(), method = method, sites = sites, richness = specaccum, sd = sdaccum, perm = perm) if (!is.null(w)) { out$weights <- weights out$effort <- xout } if (method == "rarefaction") out$individuals <- ind ## return 'freq' for methods that are solely defined by them if (method %in% c("exact", "rarefaction", "coleman")) out$freq <- freq if (method == "random") attr(out, "control") <- attr(permat, "control") class(out) <- "specaccum" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/specaccum.R
`specnumber` <- function(x, groups, MARGIN = 1) { if (!missing(groups)) { if (length(groups) == 1) groups <- rep(groups, nrow(x)) x <- aggregate(x, list(groups), max) rownames(x) <- x[,1] x <- x[,-1] } if (length(dim(x)) > 1) apply(x > 0, MARGIN, sum) else sum(x > 0) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/specnumber.R
`specpool` <- function (x, pool, smallsample = TRUE) { x <- as.matrix(x) if (!(is.numeric(x) || is.logical(x))) stop("input data must be numeric") if (missing(pool)) pool <- rep("All", nrow(x)) ## check dims if (length(pool) != NROW(x)) stop("length of 'pool' and number rows in 'x' do not match") ## remove missing values if (any(nas <- is.na(pool))) { pool <- pool[!nas] x <- x[!nas, , drop = FALSE] } out <- seq(1:nrow(x)) groups <- table(pool) inds <- names(groups) S <- var.chao <- chao <- var.jack1 <- jack.1 <- jack.2 <- var.boot <- bootS <- rep(NA, length(inds)) names(S) <- names(var.chao) <- names(chao) <- names(var.jack1) <- names(jack.1) <- names(jack.2) <- names(var.boot) <- names(bootS) <- inds for (is in inds) { a1 <- a2 <- NA gr <- out[pool == is] n <- length(gr) if (n <= 0) next if (smallsample) ssc <- (n-1)/n else ssc <- 1 X <- x[gr, , drop = FALSE] freq <- colSums(X > 0) p <- freq[freq > 0]/n S[is] <- sum(freq > 0) if (S[is] == 0) next if (n >= 1L) a1 <- sum(freq == 1) if (n >= 2L) a2 <- sum(freq == 2) else a2 <- 0 chao[is] <- S[is] + if(!is.na(a2) && a2 > 0) ssc * a1 * a1/2/a2 else ssc * a1 * (a1-1)/2 jack.1[is] <- S[is] + a1 * (n - 1)/n if (n > 1L) jack.2[is] <- S[is] + a1 * (2 * n - 3)/n - a2 * (n - 2)^2/n/(n - 1) else jack.2[is] <- S[is] bootS[is] <- S[is] + sum((1 - p)^n) aa <- if (!is.na(a2) && a2 > 0) a1/a2 else 0 if (!is.na(a2) && a2 > 0) var.chao[is] <- a1 * ssc * (0.5 + ssc * (1 + aa/4) * aa) * aa else var.chao[is] <- ssc * (ssc * (a1*(2*a1-1)^2/4 - a1^4/chao[is]/4) + a1*(a1-1)/2) if (!is.na(a1) && a1 > 0) { jf <- table(rowSums(X[, freq == 1, drop = FALSE] > 0)) var.jack1[is] <- (sum(as.numeric(names(jf))^2 * jf) - a1/n) * (n - 1)/n } else { var.jack1[is] <- 0 } pn <- (1 - p)^n X <- X[, freq > 0, drop = FALSE] Zp <- (crossprod(X == 0)/n)^n - outer(pn, pn, "*") var.boot[is] <- sum(pn * (1 - pn)) + 2 * sum(Zp[lower.tri(Zp)]) } out <- list(Species = S, chao = chao, chao.se = sqrt(var.chao), jack1 = jack.1, jack1.se = sqrt(var.jack1), jack2 = jack.2, boot = bootS, boot.se = sqrt(var.boot), n = as.vector(groups)) out <- as.data.frame(out) attr(out, "pool") <- pool out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/specpool.R
"specpool2vect" <- function(X, index = c("jack1","jack2", "chao", "boot", "Species")) { pool <- attr(X, "pool") index <- match.arg(index) X[[index]][pool] }
/scratch/gouwar.j/cran-all/cranData/vegan/R/specpool2vect.R
#' The Slope of Species Accumulation Curve at Given Point #' #' Function evaluates the derivative of the species accumulation curve #' for accumulation methods built upon analytic accumulation #' methods. These methods are \code{exact}, \code{rarefaction} and #' \code{coleman}. These methods can be evaluated at any sample size, #' including non-integer values. For other methods, you must look at #' the differences between consecutive steps, using #' \code{diff(predict(mod))}. #' #' @param object \code{specaccum} result object fitted with methods #' \code{"exact"}, \code{"rarefaction"} or \code{"coleman"}. #' @param at The sample size (number of sites) at which the slope is #' evaluated. This need not be an integer. `specslope` <- function(object, at) { UseMethod("specslope") } `specslope.specaccum` <- function(object, at) { accepted <- c("exact", "rarefaction", "coleman") if (!(object$method %in% accepted)) stop(gettextf("accumulation method must be one of: %s", paste(accepted, collapse=", "))) ## Funcions should accept a vector of 'at', but usually they ## don't. I don't care to change this, and therefore we check the ## input. if (length(at) > 1 && object$method %in% c("exact", "coleman")) stop("'at' can only have a single value") ## The following functions are completely defined by species ## frequencies f <- object$freq n <- length(object$sites) switch(object$method, exact = { d <- digamma(pmax(n-at+1, 1)) - digamma(pmax(n-f-at+1, 1)) g <- lgamma(pmax(n-f+1,1)) + lgamma(pmax(n-at+1,1)) - lgamma(pmax(n-f-at+1, 1)) - lgamma(n+1) d <- d*exp(g) sum(d[is.finite(d)]) }, rarefaction = { ## fractional number of individuals at 'at', and slope ## for adding whole site instead of one individual rareslope(f, at/n*sum(f)) * sum(f)/n }, coleman = { sum((1 - at/n)^f*f/(n - at)) }) } ## Analytical derivatives for NLS regression models in fitspecaccum `specslope.fitspecaccum` <- function(object, at) { ## functions for single set of fitted parameters. Parameters are ## given as a single vector 'p' as returned by coef(). Below a ## table of original names of 'p': ## arrhenius, gitay, gleason: k slope ## lomolino: Asym xmid slope ## asymp: Asym RO lrc ## gompertz: Asym b2 b3 ## michaelis-menten: Vm K (function SSmicmen) ## logis: Asym xmid scal ## weibull: Asym Drop lrc pwr slope <- switch(object$SSmodel, "arrhenius" = function(x,p) p[1]*x^(p[2]-1)*p[2], "gitay" = function(x,p) 2*(p[1]+p[2]*log(x))*p[2]/x, "gleason" = function(x,p) p[2]/x, "lomolino" = function(x,p) p[1]*p[3]^log(p[2]/x)*log(p[3])/ (1+p[3]^log(p[2]/x))^2/x, "asymp" = function(x,p) (p[1]-p[2])*exp(p[3]-exp(p[3])*x), "gompertz" = function(x,p) -p[1]*p[2]*p[3]^x* log(p[3])*exp(-p[2]*p[3]^x), "michaelis-menten" = function(x,p) p[1]*p[2]/(p[2]+x)^2, "logis" = function(x,p) p[1]*exp((x-p[2])/p[3])/ (1 + exp((x-p[2])/p[3]))^2/p[3], "weibull" = function(x, p) p[2]*exp(p[3]-exp(p[3])*x^p[4])* x^(p[4]-1)*p[4]) ## Apply slope with fitted coefficients at 'at' p <- coef(object) if (is.matrix(p)) # several fitted models out <- apply(p, 2, function(i) slope(at, i)) else # single site drops to a vector out <- slope(at, p) names(out) <- NULL out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/specslope.R
`spenvcor` <- function (object) { if (is.null(object$CCA)) stop("needs results from constrained ordination") u <- object$CCA$u wa <- object$CCA$wa if (!inherits(object, "rda")) { # is CCA r <- sqrt(object$rowsum) u <- r * u wa <- r * wa } ## because colSums(u*u) = 1, we can simplify diag(cor(u, wa)) -- ## and we must for weighted CA colSums(u * wa)/sqrt(colSums(wa^2)) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/spenvcor.R
#' Add Species Scores to Ordination Results #' #' @param object Ordination object #' @param value Community data #' `sppscores<-` <- function(object, value) { UseMethod("sppscores<-") } ## dbrda `sppscores<-.dbrda` <- function(object, value) { object$vdata <- deparse(substitute(value)) value <- scale(value, center = TRUE, scale = FALSE) object$colsum <- apply(value, 2, sd) ## pCCA step looks redundant: see comments in commit d915763d if (!is.null(object$pCCA) && object$pCCA$rank > 0) { value <- qr.resid(object$pCCA$QR, value) } if (!is.null(object$CCA) && object$CCA$rank > 0) { v <- crossprod(value, object$CCA$u) v <- decostand(v, "normalize", MARGIN = 2) object$CCA$v <- v value <- qr.resid(object$CCA$QR, value) } if (!is.null(object$CA) && object$CA$rank > 0) { v <- crossprod(value, object$CA$u) v <- decostand(v, "normalize", MARGIN = 2) object$CA$v <- v } object } ## capscale may have species scores, but is otherwise similar to dbrda `sppscores<-.capscale` <- function(object, value) { object <- `sppscores<-.dbrda`(object, value) object$vdata <- deparse(substitute(value)) object } ## metaMDS `sppscores<-.metaMDS` <- function(object, value) { wa <- wascores(object$points, value, expand = TRUE) attr(wa, "data") <- deparse(substitute(value)) object$species <- wa object } ## the main purpose of accessor function is to provide nicer command ## autocompletion and cross-references in help, and of course, to tell ## that it is not implemented (and may never be) `sppscores` <- function(object) { .NotYetImplemented() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/sppscores.R
`stepacross` <- function (dis, path = "shortest", toolong = 1, trace = TRUE, ...) { path <- match.arg(path, c("shortest", "extended")) if (!inherits(dis, "dist")) dis <- as.dist(dis) oldatt <- attributes(dis) n <- attr(dis, "Size") if (path == "shortest") dis <- .C(dykstrapath, dist = as.double(dis), n = as.integer(n), as.double(toolong), as.integer(trace), out = double(length(dis)), NAOK = TRUE)$out else dis <- .C(C_stepacross, dis = as.double(dis), as.integer(n), as.double(toolong), as.integer(trace), NAOK = TRUE)$dis if("maxdist" %in% oldatt) oldatt$maxdist <- NA attributes(dis) <- oldatt attr(dis, "method") <- paste(attr(dis, "method"), path) dis }
/scratch/gouwar.j/cran-all/cranData/vegan/R/stepacross.R
`str.nullmodel` <- function(object, ...) str(as.list(object), ...)
/scratch/gouwar.j/cran-all/cranData/vegan/R/str.nullmodel.R
`stressplot`<- function(object, ...) { UseMethod("stressplot") } `stressplot.monoMDS` <- function(object, pch, p.col = "blue", l.col = "red", lwd, ...) { if (missing(lwd)) if (object$ngrp > 2) lwd <- 1 else lwd <- 2 ## extract items to plot x <- object$diss y <- object$dist yf <- object$dhat ## all models plot dist against diss, but there can be duplicated ## items in some models: remove duplicates in hybrid (iregn==3) ## and local (ngrp > 1) models: if (object$iregn == 3) pts <- seq_along(x) < object$istart[2] else if (object$ngrp > 2) pts <- object$iidx > object$jidx else pts <- !logical(length(x)) ## Plotting character if (missing(pch)) if (sum(pts) > 5000) pch <- "." else pch <- 1 ## plot points plot(x[pts], y[pts], pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) ## collect values for 'linear fit' ralscal <- 0 ## Fit lines: linear (iregn=2) and hybrid (iregn=3) have a smooth line if (object$iregn > 1) { if (object$iregn == 3) { k <- seq(object$istart[2], object$ndis) yl <- range(yf[k]) xl <- range(x[k]) ralscal <- cor(y[k], yf[k])^2 } else { yl <- range(yf) xl <- range(x) ralscal <- cor(y, yf)^2 } lines(xl, yl, col = l.col, lwd = lwd, ...) } ## Monotone line except in linear, and local has several... if (object$iregn != 2) { ist <- c(object$istart, object$ndis + 1) if (object$iregn == 3) object$ngrp <- 1 for(j in 1:object$ngrp) { k <- seq(ist[j], ist[j+1]-1) ralscal <- ralscal + cor(y[k], yf[k])^2 lines(x[k], yf[k], type = "S", col = l.col, lwd = lwd, ...) } } ## Stress as R2 rstress <- 1 - object$stress^2 ralscal <- if(object$iregn == 3) ralscal/2 else ralscal/object$ngrp Rst <- format(rstress, digits = 3) Ral <- format(ralscal, digits = 3) lab1 <- bquote("Non-metric fit, " * R^2 == .(Rst)) lab2 <- bquote("Linear fit, " * R^2 == .(Ral)) text(min(x), 0.95*max(y), lab1, pos=4) text(min(x), 0.95*max(y) - strheight(lab1), lab2, pos=4) ## we want to have invisible return lists in the input order o <- order(object$jidx, object$iidx) invisible(list("x" = x[o], "y" = y[o], "yf" = yf[o])) } `stressplot.default` <- function(object, dis, pch, p.col = "blue", l.col = "red", lwd = 2, ...) { ## the default function only works with metaMDS or MASS::isoMDS results if (!(inherits(object, "metaMDS") || all(c("points", "stress") %in% names(object)))) stop("can be used only with objects that are compatible with MASS::isoMDS results") if (missing(dis)) if (inherits(object, "metaMDS")) dis <- metaMDSredist(object) else stop("needs dissimilarities 'dis'") if (attr(dis, "Size") != nrow(object$points)) stop("dimensions do not match in ordination and dissimilarities") shep <- Shepard(dis, object$points) stress <- sum((shep$y - shep$yf)^2)/sum(shep$y^2) rstress <- 1 - stress ralscal <- cor(shep$y, shep$yf)^2 stress <- sqrt(stress)*100 if ( abs(stress - object$stress) > 0.001) stop("dissimilarities and ordination do not match") if (missing(pch)) if (length(dis) > 5000) pch <- "." else pch <- 1 plot(shep, pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) lines(shep$x, shep$yf, type = "S", col = l.col, lwd = lwd, ...) Rst <- format(rstress, digits = 3) Ral <- format(ralscal, digits = 3) lab1 <- bquote("Non-metric fit, " * R^2 == .(Rst)) lab2 <- bquote("Linear fit, " * R^2 == .(Ral)) text(min(shep$x), 0.95*max(shep$y), lab1, pos=4) text(min(shep$x), 0.95*max(shep$y) - strheight(lab1), lab2, pos=4) invisible(shep) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/stressplot.R
### stressplot() methods for eigenvector ordinations wcmdscale, rda, ### cca, capscale, dbrda `stressplot.wcmdscale` <- function(object, k = 2, pch, p.col = "blue", l.col = "red", lwd = 2, ...) { ## Check that original distances can be reconstructed: this ## requires that all axes were calculated instead of 'k' first. hasdims <- NCOL(object$points) if (!is.null(object$negaxes)) hasdims <- hasdims + NCOL(object$negaxes) if (hasdims < length(object$eig)) stop("observed distances cannot be reconstructed: all axes were not calculated") ## Get the ordination distances in k dimensions if (k > NCOL(object$points)) warning(gettextf("max allowed rank is k = %d", NCOL(object$points))) k <- min(NCOL(object$points), k) w <- sqrt(object$weights) u <- diag(w) %*% object$points odis <- dist(u[,1:k, drop = FALSE]) ## Reconstitute the original observed distances dis <- dist(u) if (!is.null(object$negaxes)) dis <- sqrt(dis^2 - dist(diag(w) %*% object$negaxes)^2) ## Remove additive constant to get original dissimilarities if (!is.na(object$ac)) { if (object$add == "lingoes") dis <- sqrt(dis^2 - 2 * object$ac) else if (object$add == "cailliez") dis <- dis - object$ac else stop("unknown Euclidifying adjustment: no idea what to do") } ##Plot if (missing(pch)) if (length(dis) > 5000) pch <- "." else pch <- 1 plot(dis, odis, pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) abline(0, 1, col = l.col, lwd = lwd, ...) invisible(odis) } `stressplot.rda` <- function(object, k = 2, pch, p.col = "blue", l.col = "red", lwd = 2, ...) { ## Normalized scores to reconstruct data u <- cbind(object$CCA$u, object$CA$u) v <- cbind(object$CCA$v, object$CA$v) ev <- c(object$CCA$eig, object$CA$eig) ## check that k does not exceed rank if (k > length(ev)) { warning(gettextf("max allowed rank is k = %d", length(ev))) k <- min(k, length(ev)) } ## normalizing constant nr <- NROW(u) const <- sqrt(ev * (nr-1)) u <- u %*% diag(const, length(const)) ## Distances Xbar <- u %*% t(v) Xbark <- u[, seq_len(k), drop = FALSE] %*% t(v[, seq_len(k), drop = FALSE]) if (!is.null(object$pCCA)) { pFit <- ordiYbar(object, "pCCA") * sqrt(nr-1) Xbar <- Xbar + pFit Xbark <- Xbark + pFit } dis <- dist(Xbar) odis <- dist(Xbark) ## plot like above ## Plot if (missing(pch)) if (length(dis) > 5000) pch <- "." else pch <- 1 plot(dis, odis, pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) abline(0, 1, col = l.col, lwd = lwd, ...) invisible(odis) } `stressplot.cca` <- function(object, k = 2, pch, p.col = "blue", l.col = "red", lwd = 2, ...) { ## Normalized scores to reconstruct data u <- cbind(object$CCA$u, object$CA$u) sev <- sqrt(c(object$CCA$eig, object$CA$eig)) w <- sqrt(object$rowsum) u <- diag(w) %*% u %*% diag(sev, length(sev)) v <- cbind(object$CCA$v, object$CA$v) v <- diag(sqrt(object$colsum)) %*% v ## check that k <= rank if (k > length(sev)) { warning(gettextf("max allowed rank is k = %d", length(sev))) k <- min(k, length(sev)) } ## Distances Xbar <- u %*% t(v) Xbark <- u[,seq_len(k), drop = FALSE] %*% t(v[,seq_len(k), drop = FALSE]) if (!is.null(object$pCCA)) { pFit <- ordiYbar(object, "pCCA") Xbar <- Xbar + pFit Xbark <- Xbark + pFit } dis <- dist(Xbar) odis <- dist(Xbark) ## Plot if (missing(pch)) if (length(dis) > 5000) pch <- "." else pch <- 1 plot(dis, odis, pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) abline(0, 1, col = l.col, lwd = lwd, ...) invisible(odis) } `stressplot.capscale` <- function(object, k = 2, pch, p.col = "blue", l.col = "red", lwd = 2, ...) { ## Scores to reconstruct data u <- cbind(object$CCA$u, object$CA$u) ## check rank if (k > NCOL(u)) warning(gettextf("max allowed rank is k = %d", ncol(u))) k <- min(k, ncol(u)) ev <- c(object$CCA$eig, object$CA$eig) u <- u %*% diag(sqrt(ev) * object$adjust, length(ev)) ## Constrained ordination needs also scores 'v' to reconstruct ## 'data', but these are not returned by capscale() which replaces ## original 'v' with weighted sums of 'comm' data. if (!is.null(object$CCA)) v <- svd(ordiYbar(object, "CCA"), nu = 0, nv = object$CCA$qrank)$v else v <- NULL if (!is.null(object$CA)) v <- cbind(v, svd(ordiYbar(object, "CA"), nu = 0, nv = object$CA$rank)$v) ## Reconstruct Xbar and Xbark Xbar <- u %*% t(v) Xbark <- u[,seq_len(k), drop = FALSE] %*% t(v[,seq_len(k), drop = FALSE]) if (!is.null(object$pCCA)) { pFit <- ordiYbar(object, "pCCA") Xbar <- Xbar + pFit Xbark <- Xbark + pFit } ## Distances dis <- dist(Xbar) odis <- dist(Xbark) if (!is.null(object$CA$imaginary.u.eig)) { dis <- dis^2 - dist(object$CA$imaginary.u.eig)^2 if (all(dis > -sqrt(.Machine$double.eps))) dis <- sqrt(pmax(dis, 0)) else # neg dis will be NaN with a warning dis <- sqrt(dis) } ## Remove additive constant to get original dissimilarities if (!is.null(object$ac)) { if (object$add == "lingoes") dis <- sqrt(dis^2 - 2 * object$ac) else if (object$add == "cailliez") dis <- dis - object$ac else stop("unknown Euclidifying adjustment: no idea what to do") } ## undo internal sqrt.dist if (object$sqrt.dist) dis <- dis^2 ## plot like above ## Plot if (missing(pch)) if (length(dis) > 5000) pch <- "." else pch <- 1 plot(dis, odis, pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) abline(0, 1, col = l.col, lwd = lwd, ...) invisible(odis) } ### dbrda() returns only row scores 'u' (LC scores for constraints, ### site scores for unconstrained part), and these can be used to ### reconstitute dissimilarities only in unconstrained ordination or ### for constrained component. `stressplot.dbrda` <- function(object, k = 2, pch, p.col = "blue", l.col = "red", lwd = 2, ...) { ## Reconstructed zero distances can be tiny (negative) non-zero ## values, and we zap them to zero ZAP <- sqrt(.Machine$double.eps) ## Reconstruct original distances from Gower 'G' dis <- ordiYbar(object, "initial") dia <- diag(dis) dis <- -2 * dis + outer(dia, dia, "+") dis[abs(dis) < ZAP] <- 0 dis <- sqrt(as.dist(dis)) * object$adjust ## Remove additive constant to get original dissimilarities if (!is.null(object$ac)) { if (object$add == "lingoes") dis <- sqrt(dis^2 - 2 * object$ac) else if (object$add == "cailliez") dis <- dis - object$ac else stop("unknown Euclidifying adjustment: no idea what to do") } ## undo internal sqrt.dist if (object$sqrt.dist) dis <- dis^2 ## Approximate dissimilarities from real components. Can only be ## used for one component. if (is.null(object$CCA)) { U <- object$CA$u eig <- object$CA$eig } else { U <- object$CCA$u eig <- object$CCA$eig } eig <- eig[eig > 0] ## check that 'k' does not exceed real rank if (k > ncol(U)) warning(gettextf("max allowed rank is k = %d", ncol(U))) k <- min(k, ncol(U)) Gk <- tcrossprod(sweep(U[, seq_len(k), drop=FALSE], 2, sqrt(eig[seq_len(k)]), "*")) dia <- diag(Gk) odis <- -2 * Gk + outer(dia, dia, "+") odis[abs(odis) < ZAP] <- 0 odis <- sqrt(as.dist(odis)) * object$adjust ## Plot if (missing(pch)) if (length(dis) > 5000) pch <- "." else pch <- 1 plot(dis, odis, pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) abline(0, 1, col = l.col, lwd = lwd, ...) invisible(odis) } ## Standard R PCA functions `stressplot.prcomp` <- function(object, k = 2, pch, p.col = "blue", l.col = "red", lwd = 2, ...) { dis <- dist(object$x) odis <- dist(object$x[, 1:k, drop = FALSE]) if (missing(pch)) if (length(dis) > 5000) pch <- "." else pch <- 1 plot(dis, odis, pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) abline(0, 1, col = l.col, lwd = lwd, ...) invisible(odis) } `stressplot.princomp` <- function(object, k = 2, pch, p.col = "blue", l.col = "red", lwd = 2, ...) { dis <- dist(object$scores) odis <- dist(object$scores[, 1:k, drop = FALSE]) if (missing(pch)) if (length(dis) > 5000) pch <- "." else pch <- 1 plot(dis, odis, pch = pch, col = p.col, xlab = "Observed Dissimilarity", ylab = "Ordination Distance", ...) abline(0, 1, col = l.col, lwd = lwd, ...) invisible(odis) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/stressplot.wcmdscale.R
`summary.anosim` <- function (object, ...) { print(object) if (object$permutations) { out <- quantile(object$perm, c(0.9, 0.95, 0.975, 0.99)) cat("Upper quantiles of permutations (null model):\n") print(out, digits=3) } cat("\n") tmp <- tapply(object$dis.rank, object$class.vec, quantile) out <- matrix(NA, length(tmp), 5) for (i in seq_along(tmp)) { if (!is.null(tmp[[i]])) out[i,] <- tmp[[i]] } rownames(out) <- names(tmp) colnames(out) <- names(tmp$Between) out <- cbind(out, N = table(object$class.vec)) cat("Dissimilarity ranks between and within classes:\n") print(out) cat("\n") invisible() }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.anosim.R
"summary.bioenv" <- function(object, ...) { x <- object$models nam <- object$names size <- seq_along(x) cor <- unlist(lapply(x, function(tmp) tmp$est)) pars <- unlist(lapply(x, function(tmp) paste(nam[tmp$best], collapse=" "))) out <- list(size = size, correlation = cor, variables = pars) class(out) <- "summary.bioenv" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.bioenv.R
`summary.cca` <- function (object, scaling = "species", axes = 6, display=c("sp","wa","lc","bp","cn"), digits = max(3, getOption("digits") - 3), correlation = FALSE, hill = FALSE, ...) { axes <- min(axes, sum(object$CCA$rank, object$CA$rank)) summ <- list() ## scaling is stored in return object so must be in numeric format scaling <- scalingType(scaling = scaling, correlation = correlation, hill = hill) if (axes && length(display) && !anyNA(display) && !is.null(display)) summ <- scores(object, scaling = scaling, choices = 1:axes, display = display, ...) ## scores() drops list to a matrix if there is only one item: workaround below. if (!is.list(summ) && length(display) == 1) { nms <- c("species", "sites", "constraints", "biplot", "centroids") names(nms) <- c("sp","wa","lc","bp","cn") summ <- list(summ) names(summ) <- nms[display] } if (length(display) > 0) { for (i in seq_along(summ)) { if (is.matrix(summ[[i]])) rownames(summ[[i]]) <- rownames(summ[[i]], do.NULL = FALSE, prefix = substr(names(summ)[i], 1, 3)) } } summ$call <- object$call summ$tot.chi <- object$tot.chi ## only the Real component for capscale() with negative eigenvalues if (!is.null(object$CA$imaginary.chi)) summ$tot.chi <- summ$tot.chi - object$CA$imaginary.chi summ$partial.chi <- object$pCCA$tot.chi summ$constr.chi <- object$CCA$tot.chi summ$unconst.chi <- object$CA$tot.chi ## nested list cont$importance needed to keep vegan pre-2.5-0 compatibility summ$cont$importance <- summary(eigenvals(object)) if (!is.null(object$CCA) && object$CCA$rank > 0) summ$concont$importance <- summary(eigenvals(object, model = "constrained")) summ$ev.head <- c(summ$ev.con, summ$ev.uncon)[seq_len(axes)] summ$scaling <- scaling summ$digits <- digits summ$inertia <- object$inertia summ$method <- object$method class(summ) <- "summary.cca" summ }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.cca.R
summary.clamtest <- function(object, ...) { structure(c(attr(object, "settings"), list(summary=cbind(Species=table(object$Classes), Proportion=table(object$Classes)/nrow(object)), minv=attr(object, "minv"), coverage=attr(object, "coverage"))), class="summary.clamtest") }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.clamtest.R
"summary.decorana" <- function (object, digits = 3, origin = TRUE, display = c("both", "species", "sites", "none"), ...) { display <- match.arg(display) print(object) if (origin) { object$cproj <- sweep(object$cproj, 2, object$origin, "-") object$rproj <- sweep(object$rproj, 2, object$origin, "-") } tmp <- list() if (display == "both" || display == "species") { tmp$spec.scores <- object$cproj tmp$spec.priorweights <- object$v tmp$spec.totals <- object$adotj } if (display == "both" || display == "sites") { tmp$site.scores <- object$rproj tmp$site.totals <- object$aidot } tmp$digits <- digits class(tmp) <- "summary.decorana" tmp }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.decorana.R
### summary methods extracts dispweight attributes, and prints a table ### of dispersion statistics `summary.dispweight` <- function(object, ...) { x <- attributes(object) class(x) <- "summary.dispweight" x } `print.summary.dispweight` <- function(x, ...) { tab <- with(x, cbind(D, weights, df, p)) colnames(tab) <- c("Dispersion", "Weight", "Df", "Pr(Disp.)") printCoefmat(tab, cs.ind = NA, ...) if (!is.na(x$nsimul)) cat(sprintf("Based on %d simulations on '%s' nullmodel\n", x$nsimul, x$nullmodel)) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.dispweight.R
`summary.isomap` <- function (object, axes=4, ...) { axes <- min(axes, ncol(object$points)) out <- list() out$call <- object$call out$points <- object$points[,1:axes] out$net <- object$net n <- nrow(object$points) out$ndis <- n * (n-1) / 2 out$nnet <- nrow(object$net) class(out) <- "summary.isomap" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.isomap.R
`summary.meandist` <- function(object, ...) { n <- attr(object, "n") wmat <- n %o% n diag(wmat) <- diag(wmat) - n ## mean distances within, between groups and in total W <- weighted.mean(diag(object), w = diag(wmat), na.rm = TRUE) B <- weighted.mean(object[lower.tri(object)], w = wmat[lower.tri(wmat)], na.rm = TRUE) D <- weighted.mean(object, w = wmat, na.rm = TRUE) ## Variants of MRPP statistics A1 <- weighted.mean(diag(object), w = n, na.rm = TRUE) A2 <- weighted.mean(diag(object), w = n - 1, na.rm = TRUE) A3 <- weighted.mean(diag(object), w = n * (n - 1), na.rm = TRUE) ## out <- list(W = W, B = B, D = D, CS = B-A1, A1 = 1 - A1/D, A2 = 1 - A2/D, A3 = 1 - A3/D) class(out) <- "summary.meandist" out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.meandist.R
### Centres and areas of plotted ellipses. The principal axes of the ### conic (oblique ellipse) are found from the eigenvalues of the ### covariance matrix. `summary.ordiellipse` <- function(object, ...) { cnts <- sapply(object, function(x) x$center) ## 2nd eigenvalue should be zero if points are on line (like two ## points), but sometimes it comes out negative, and area is NaN areas <- sapply(object, function(x) sqrt(pmax(0, det(x$cov))) * pi * x$scale^2) rbind(cnts, `Area` = areas) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.ordiellipse.R
### Centres and areas of convex hulls (simple polygons). `summary.ordihull` <- function(object, ...) { polyarea <- function(x) { n <- nrow(x) if (n < 4) return(0) else abs(sum(x[-n,1]*x[-1,2] - x[-1,1]*x[-n,2]))/2 } 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 structure(c(xc, yc), names = colnames(x)) } areas <- sapply(object, function(x) polyarea(x)) cnts <- sapply(object, function(x) polycentre(x)) rbind(cnts, `Area` = areas) }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.ordihull.R
## S3 summary method for permat `summary.permat` <- function(object, ...) { x <- object ## calculations are much faster if x$orig is matrix instead of data.frame x$orig <- data.matrix(x$orig) ss <- sum(x$orig) fi <- sum(x$orig > 0) rs <- rowSums(x$orig) cs <- colSums(x$orig) rb <- rowSums(x$orig > 0) cb <- colSums(x$orig > 0) nr <- nrow(x$orig) nc <- ncol(x$orig) bray <- sapply(x$perm, function(z) sum(abs(x$orig - z)) / sum(x$orig + z)) psum <- sapply(x$perm, function(z) ss == sum(z)) pfill <- sapply(x$perm, function(z) fi == sum(z > 0)) vrow <- sapply(x$perm, function(z) sum(rs == rowSums(z)) == nr) vcol <- sapply(x$perm, function(z) sum(cs == colSums(z)) == nc) brow <- sapply(x$perm, function(z) sum(rb == rowSums(z > 0)) == nr) bcol <- sapply(x$perm, function(z) sum(cb == colSums(z > 0)) == nc) if (attr(x, "is.strat")) { int <- attr(x, "strata") nlev <- length(unique(int)) rsagg <- rowSums(aggregate(x$orig, list(int), sum)[,-1]) ssum <- sapply(x$perm, function(z) sum(rsagg == rowSums(aggregate(z, list(int), sum)[,-1])) == nlev) } else ssum <- NULL ## Chisq E <- rs %o% cs / ss chisq <- sapply(x$perm, function(z) sum((z - E)^2 / E)) attr(chisq, "chisq.orig") <- sum((x$orig - E)^2 / E) # attr(chisq, "df") <- (nr - 1) * (nc - 1) ## ts if sequential seqmethods <- sapply(make.commsim(), function(z) make.commsim(z)$isSeq) seqmethods <- names(seqmethods)[seqmethods] # seqmethods <- c("swap", "tswap", "abuswap") if (attr(x, "method") %in% seqmethods) { startval <- attr(x, "burnin") + 1 dtime <- max(1, attr(x, "thin")) bray <- ts(bray, start = startval, deltat = dtime) chisq <- ts(chisq, start = startval, deltat = dtime) } x$perm <- NULL out <- list(x=x, bray=bray, chisq=chisq, sum=psum, fill=pfill, rowsums=vrow, colsums=vcol, browsums=brow, bcolsums=bcol, strsum=ssum) class(out) <- c("summary.permat", "list") out }
/scratch/gouwar.j/cran-all/cranData/vegan/R/summary.permat.R