content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
###
### Editable Tcl/Tk plot for ordination
###
`orditkplot` <-
function(x, display = "species", choices = 1:2, width, xlim, ylim,
tcex=0.8, tcol, pch = 1, pcol, pbg, pcex = 0.7,
labels, ...)
{
if (!capabilities("tcltk"))
stop("your R has no capability for Tcl/Tk")
requireNamespace("tcltk") || stop("requires package tcltk")
############################
### Check and sanitize input
###########################
## Graphical parameters and constants, and save some for later plotting
p <- par()
sparnam <- c("bg","cex", "cex.axis","cex.lab","col", "col.axis", "col.lab",
"family", "fg", "font", "font.axis", "font.lab", "lheight",
"lwd", "mar", "mex", "mgp", "ps", "tcl", "las")
## Get par given in the command line and put them to p
if (inherits(x, "orditkplot")) {
dots <- x$par
for (arg in names(x$args))
assign(arg, unlist(x$args[arg]))
} else {
dots <- match.call(expand.dots = FALSE)$...
}
if (length(dots) > 0) {
dots <- dots[names(dots) %in% sparnam]
## eval() or mar=c(4,4,1,1) will be a call, not numeric
dots <- lapply(dots, function(x) if (is.call(x)) eval(x) else x)
p <- check.options(new = dots, name.opt = "p",
envir = environment())
}
savepar <- p[sparnam]
PPI <- 72 # Points per Inch
p2p <- as.numeric(tcltk::tclvalue(tcltk::tcl("tk", "scaling"))) # Pixel per point
DIAM <- 2.7 # diam of plotting symbol
## Plotting symbol diam
diam <- round(pcex * DIAM * p2p, 1)
## Sanitize colours
sanecol <- function(x) {
if (is.numeric(x))
x <- palette()[x]
x <- gsub("transparent", "", x)
x[is.na(x)] <- ""
x
}
p$bg <- sanecol(p$bg)
p$fg <- sanecol(p$fg)
p$col <- sanecol(p$col)
p$col.axis <- sanecol(p$col.axis)
p$col.lab <- sanecol(p$col.lab)
## Point and label colours
if (missing(pcol))
pcol <- p$col
if (missing(pbg))
pbg <- "transparent"
if (missing(tcol))
tcol <- p$col
pcol <- sanecol(pcol)
pbg <- sanecol(pbg)
tcol <- sanecol(tcol)
## Define fonts
idx <- match(p$family, c("","serif","sans","mono"))
if (!is.na(idx))
p$family <- c("Helvetica", "Times", "Helvetica", "Courier")[idx]
saneslant <- function(x) {
list("roman", "bold", "italic", c("bold", "italic"))[[x]]
}
## fnt must be done later, since family, font and size can be
## vectors and slant can be of length 1 or 2
## fnt <- c(p$family, round(p$ps*p$cex*tcex), saneslant(p$font))
labfam <- p$family
labsize <- round(p$ps * p$cex * tcex)
fnt.axis <- c(p$family, round(p$ps*p$cex.axis), saneslant(p$font.axis))
fnt.lab <- c(p$family, round(p$ps*p$cex.lab), saneslant(p$font.lab))
## Imitate R plotting symbols pch
SQ <- sqrt(2) # Scaling factor for plot
Point <- function(x, y, pch, col, fill, diam) {
x <- round(x)
y <- round(y)
switch(as.character(pch),
"0" = Point(x, y, 22, col, fill = "", diam),
"1" = Point(x, y, 21, col, fill = "", diam),
"2" = Point(x, y, 24, col, fill = "", diam),
"3" = {tcltk::tkcreate(can, "line",
x, y+SQ*diam, x, y-SQ*diam, fill=col)
tcltk::tkcreate(can, "line",
x+SQ*diam, y, x-SQ*diam, y, fill=col)},
"4" = {tcltk::tkcreate(can, "line",
x-diam, y-diam, x+diam, y+diam, fill=col)
tcltk::tkcreate(can, "line",
x-diam, y+diam, x+diam, y-diam, fill=col)},
"5" = Point(x, y, 23, col, fill = "", diam),
"6" = Point(x, y, 25, col, fill = "", diam),
"7" = {Point(x, y, 4, col, fill, diam)
Point(x, y, 0, col, fill, diam)},
"8" = {Point(x, y, 3, col, fill, diam)
Point(x, y, 4, col, fill, diam)},
"9" = {Point(x, y, 3, col, fill, diam)
Point(x, y, 5, col, fill, diam)},
"10" = {Point(x, y, 3, col, fill, diam/SQ)
Point(x, y, 1, col, fill, diam)},
"11" = {Point(x, y, 2, col, fill, diam)
Point(x, y, 6, col, fill, diam)},
"12" = {Point(x, y, 3, col, fill, diam/SQ)
Point(x, y, 0, col, fill, diam)},
"13" = {Point(x, y, 4, col, fill, diam)
Point(x, y, 1, col, fill, diam)},
"14" = {tcltk::tkcreate(can, "line", x-diam, y-diam, x, y+diam,
fill = col)
tcltk::tkcreate(can, "line", x+diam, y-diam, x, y+diam,
fill = col)
Point(x, y, 0, col, fill, diam)},
"15" = Point(x, y, 22, col = col, fill = col, diam),
"16" = Point(x, y, 21, col = col, fill = col, diam),
"17" = Point(x, y, 24, col = col, fill = col, diam),
"18" = Point(x, y, 23, col = col, fill = col, diam/SQ),
"19" = Point(x, y, 21, col = col, fill = col, diam),
"20" = Point(x, y, 21, col = col, fill = col, diam/2),
"21" = tcltk::tkcreate(can, "oval", x-diam, y-diam,
x+diam, y+diam, outline = col, fill = fill),
"22" = tcltk::tkcreate(can, "rectangle", x-diam, y-diam,
x+diam, y+diam, outline = col, fill = fill),
"23" = tcltk::tkcreate(can, "polygon", x, y+SQ*diam,
x+SQ*diam, y, x, y-SQ*diam, x-SQ*diam, y,
outline = col, fill = fill),
"24" = tcltk::tkcreate(can, "polygon", x, y-SQ*diam,
x+sqrt(6)/2*diam, y+SQ/2*diam, x-sqrt(6)/2*diam, y+SQ/2*diam,
outline = col, fill = fill),
"25" = tcltk::tkcreate(can, "polygon", x, y+SQ*diam,
x+sqrt(6)/2*diam, y-SQ/2*diam, x-sqrt(6)/2*diam, y-SQ/2*diam,
outline = col, fill = fill),
"o" = Point(x, y, 1, col, fill, diam),
## default: text with dummy location of the label
{tcltk::tkcreate(can, "text",
x, y, text = as.character(pch), fill = col)
Point(x, y, 21, col="", fill="", diam)}
)
}
############################
### Initialize Tcl/Tk Window
############################
## toplevel
w <- tcltk::tktoplevel()
tcltk::tktitle(w) <- deparse(match.call())
## Max dim of windows (depends on screen)
YSCR <- as.numeric(tcltk::tkwinfo("screenheight", w)) - 150
XSCR <- as.numeric(tcltk::tkwinfo("screenwidth", w))
################################
### Buttons and button functions
################################
## Buttons
buts <- tcltk::tkframe(w)
## Copy current canvas to EPS using the standard Tcl/Tk utility
cp2eps <- tcltk::tkbutton(buts, text="Copy to EPS",
command=function() tcltk::tkpostscript(can, x=0, y=0,
height=height, width=width,
file=tcltk::tkgetSaveFile(
filetypes="{{EPS file} {.eps}}",
defaultextension=".eps")))
dismiss <- tcltk::tkbutton(buts, text="Close",
command=function() tcltk::tkdestroy(w))
## Dump current plot to an "orditkplot" object (internally)
ordDump <- function() {
xy <- matrix(0, nrow=nrow(sco), ncol=2)
rownames(xy) <- rownames(sco)
colnames(xy) <- colnames(sco)
for(nm in names(pola)) {
xy[as.numeric(tcltk::tclvalue(id[[nm]])),] <- xy2usr(nm)
}
curdim <- round(c(width, height) /PPI/p2p, 2)
## Sanitize colours for R plot
pbg[pbg == ""] <- "transparent"
pcol[pcol == ""] <- "transparent"
## Reduce vector args if all entries are constant
argcollapse <- function(x)
if (length(unique(x)) == 1) x[1] else x
pch <- argcollapse(pch)
pcol <- argcollapse(pcol)
pbg <- argcollapse(pbg)
tcol <- argcollapse(tcol)
## Save
args <- list(tcex = tcex, tcol = tcol, pch = pch, pcol = pcol,
pbg = pbg, pcex = pcex, xlim = xlim, ylim = ylim)
xy <- list(labels = xy, points = sco, par = savepar, args = args,
dim = curdim)
class(xy) <- "orditkplot"
xy
}
## Button to dump "orditkplot" object to the R session
pDump <- function() {
xy <- ordDump()
dumpVar <- tcltk::tclVar("")
tt <- tcltk::tktoplevel()
tcltk::tktitle(tt) <- "R Dump"
entryDump <- tcltk::tkentry(tt, width=20, textvariable=dumpVar)
tcltk::tkgrid(tcltk::tklabel(tt, text="Enter name for an R object"))
tcltk::tkgrid(entryDump, pady="5m")
isDone <- function() {
dumpName <- tcltk::tclvalue(dumpVar)
if (exists(dumpName, envir = parent.frame())) {
ok <- tcltk::tkmessageBox(message=paste(sQuote(dumpName),
"exists.\nOK to overwrite?"),
icon="warning", type="okcancel",
default="ok")
if(tcltk::tclvalue(ok) == "ok") {
assign(dumpName, xy, envir = parent.frame())
tcltk::tkdestroy(tt)
}
}
else {
assign(dumpName, xy, envir = parent.frame())
tcltk::tkdestroy(tt)
}
}
tcltk::tkbind(entryDump, "<Return>", isDone)
tcltk::tkfocus(tt)
}
dump <- tcltk::tkbutton(buts, text="Save to R", command=pDump)
## Button to write current "orditkplot" object to a graphical device
devDump <- function() {
xy <- ordDump()
ftypes <- c("eps" = "{EPS File} {.eps}",
"pdf" = "{PDF File} {.pdf}",
"svg" = "{SVG File} {.svg}",
"png" = "{PNG File} {.png}",
"jpg" = "{JPEG File} {.jpg .jpeg}",
"bmp" = "{BMP File} {.bmp}",
"tiff"= "{TIFF File} {.tif .tiff}",
"fig" = "{XFig File} {.fig}")
falt <- rep(TRUE, length(ftypes))
names(falt) <- names(ftypes)
if (!capabilities("png"))
falt["png"] <- FALSE
if (!capabilities("jpeg"))
falt["jpg"] <- FALSE
if (!capabilities("cairo"))
falt["svg"] <- FALSE
## Should work also in R < 2.8.0 with no capabilities("tiff")
if (!isTRUE(unname(capabilities("tiff"))))
falt["tiff"] <- FALSE
ftypes <- ftypes[falt]
## External Tcl/Tk in Windows seems to buggy with type
## extensions of the file name: the extension is not
## automatically appended, but defaultextension is interpreted
## wrongly so that its value is not used as extension but
## correct appending is done if defaultextension has any
## value. The following kluge is against Tcl/Tk documentation,
## and should be corrected if Tcl/Tk is fixed.
if (.Platform$OS.type == "windows")
fname <- tcltk::tkgetSaveFile(filetypes=ftypes,
defaultextension = TRUE)
else
fname <- tcltk::tkgetSaveFile(filetypes=ftypes)
if(tcltk::tclvalue(fname) == "")
return(NULL)
fname <- tcltk::tclvalue(fname)
ftype <- unlist(strsplit(fname, "\\."))
ftype <- ftype[length(ftype)]
if (ftype == "jpeg")
ftype <- "jpg"
if (ftype == "tif")
ftype <- "tiff"
mess <- "is not a supported type: file not produced. Supported types are"
if (!(ftype %in% names(ftypes))) {
tcltk::tkmessageBox(message=paste(sQuote(ftype), mess, paste(names(ftypes),
collapse=", ")), icon="warning")
return(NULL)
}
pixdim <- round(xy$dim*PPI*p2p)
switch(ftype,
eps = postscript(file=fname, width=xy$dim[1], height=xy$dim[2],
paper="special", horizontal = FALSE),
pdf = pdf(file=fname, width=xy$dim[1], height=xy$dim[2]),
svg = svg(filename=fname, width=xy$dim[1], height=xy$dim[2]),
png = png(filename=fname, width=pixdim[1], height=pixdim[2]),
jpg = jpeg(filename=fname, width=pixdim[1], height=pixdim[2],
quality = 100),
tiff = tiff(filename=fname, width=pixdim[1], height=pixdim[2]),
bmp = bmp(filename=fname, width=pixdim[1], height=pixdim[2]),
fig = xfig(file=fname, width=xy$dim[1], height=xy$dim[2]))
plot.orditkplot(xy)
dev.off()
}
export <- tcltk::tkbutton(buts, text="Export plot", command=devDump)
##########
### Canvas
##########
## Make canvas
sco <- try(scores(x, display=display, choices = choices, ...),
silent = TRUE)
if (inherits(sco, "try-error")) {
tcltk::tkmessageBox(message=paste("No ordination scores were found in",
sQuote(deparse(substitute(x)))), icon="error")
tcltk::tkdestroy(w)
stop("argument x did not contain ordination scores")
}
if (!missing(labels))
rownames(sco) <- labels
## Recycle graphical parameters in plots
nr <- nrow(sco)
pcol <- rep(pcol, length=nr)
pbg <- rep(pbg, length=nr)
pch <- rep(pch, length=nr)
tcol <- rep(tcol, length=nr)
diam <- rep(diam, length=nr)
labfam <- rep(labfam, length=nr)
labsize <- rep(labsize, length=nr)
if (inherits(x, "ordipointlabel"))
labfnt <- attr(x$labels, "font")
else
labfnt <- rep(p$font, length=nr)
## Select only items within xlim, ylim
take <- rep(TRUE, nr)
if (!missing(xlim))
take <- take & sco[,1] >= xlim[1] & sco[,1] <= xlim[2]
if (!missing(ylim))
take <- take & sco[,2] >= ylim[1] & sco[,2] <= ylim[2]
sco <- sco[take,, drop=FALSE]
labs <- rownames(sco)
pcol <- pcol[take]
pbg <- pbg[take]
tcol <- tcol[take]
pch <- pch[take]
diam <- diam[take]
labfam <- labfam[take]
labsize <- labsize[take]
labfnt <- labfnt[take]
## Ranges and pretty values for axes
if (missing(xlim))
xlim <- range(sco[,1], na.rm = TRUE)
if (missing(ylim))
ylim <- range(sco[,2], na.rm = TRUE)
xpretty <- pretty(xlim)
ypretty <- pretty(ylim)
## Extend ranges by 4%
xrange <- c(-0.04, 0.04) * diff(xlim) + xlim
xpretty <- xpretty[xpretty >= xrange[1] & xpretty <= xrange[2]]
yrange <- c(-0.04, 0.04) * diff(ylim) + ylim
ypretty <- ypretty[ypretty >= yrange[1] & ypretty <= yrange[2]]
## Canvas like they were in the default devices when I last checked
if (missing(width))
width <- p$din[1]
width <- width * PPI * p2p
## Margin row width also varies with platform and devices
## rpix <- (p$mai/p$mar * PPI * p2p)[1]
rpix <- p$cra[2]
mar <- round(p$mar * rpix)
xusr <- width - mar[2] - mar[4]
xincr <- xusr/diff(xrange)
yincr <- xincr
xy0 <- c(xrange[1], yrange[2]) # upper left corner
## Functions to translate scores to canvas coordinates and back
usr2xy <- function(row) {
x <- (row[1] - xy0[1]) * xincr + mar[2]
y <- (xy0[2] - row[2]) * yincr + mar[3]
c(x,y)
}
## User coordinates of an item
xy2usr <- function(item) {
xy <- as.numeric(tcltk::tkcoords(can, item))
x <- xy[1]
y <- xy[2]
x <- xrange[1] + (x - mar[2])/xincr
y <- yrange[2] - (y - mar[3])/yincr
c(x,y)
}
## Canvas x or y to user coordinates
x2usr <- function(xcan) {
xrange[1] + (xcan - mar[2])/xincr
}
y2usr <- function(ycan) {
yrange[2] - (ycan - mar[3])/yincr
}
## Equal aspect ratio
height <- round((diff(yrange)/diff(xrange)) * xusr)
height <- height + mar[1] + mar[3]
## Canvas, finally
can <- tcltk::tkcanvas(w, relief="sunken", width=width, height=min(height,YSCR),
scrollregion=c(0,0,width,height))
if (p$bg != "")
tcltk::tkconfigure(can, bg=p$bg)
yscr <- tcltk::tkscrollbar(w, command =
function(...) tcltk::tkyview(can, ...))
tcltk::tkconfigure(can, yscrollcommand =
function(...) tcltk::tkset(yscr, ...))
## Pack it up
tcltk::tkpack(buts, side="bottom", fill="x", pady="2m")
tcltk::tkpack(can, side="left", fill="x")
tcltk::tkpack(yscr, side="right", fill="y")
tcltk::tkgrid(cp2eps, export, dump, dismiss, sticky="s")
## Box
x0 <- usr2xy(c(xrange[1], yrange[1]))
x1 <- usr2xy(c(xrange[2], yrange[2]))
tcltk::tkcreate(can, "rectangle", x0[1], x0[2], x1[1], x1[2], outline = p$fg,
width = p$lwd)
## Axes and ticks
tl <- -p$tcl * rpix # -p$tcl * p$ps * p2p
axoff <- p$mgp[3] * rpix
tmp <- xpretty
for (i in seq_along(tmp)) {
x0 <- usr2xy(c(xpretty[1], yrange[1]))
x1 <- usr2xy(c(xpretty[length(xpretty)], yrange[1]))
tcltk::tkcreate(can, "line", x0[1], x0[2]+axoff, x1[1], x1[2]+axoff,
fill=p$fg)
xx <- usr2xy(c(tmp[i], yrange[1]))
tcltk::tkcreate(can, "line", xx[1], xx[2] + axoff, xx[1],
xx[2]+tl+axoff, fill=p$fg)
tcltk::tkcreate(can, "text", xx[1], xx[2] + rpix * p$mgp[2], anchor="n",
text=as.character(tmp[i]), fill=p$col.axis, font=fnt.axis)
}
xx <- usr2xy(c(mean(xrange), yrange[1]))
tcltk::tkcreate(can, "text", xx[1], xx[2] + rpix * p$mgp[1],
text=colnames(sco)[1], fill=p$col.lab, anchor="n", font=fnt.lab)
tmp <- ypretty
for (i in seq_along(tmp)) {
x0 <- usr2xy(c(xrange[1], tmp[1]))
x1 <- usr2xy(c(xrange[1], tmp[length(tmp)]))
tcltk::tkcreate(can, "line", x0[1]-axoff, x0[2], x1[1]-axoff, x1[2])
yy <- usr2xy(c(xrange[1], tmp[i]))
tcltk::tkcreate(can, "line", yy[1]-axoff, yy[2], yy[1]-tl-axoff, yy[2],
fill=p$fg )
tcltk::tkcreate(can, "text", yy[1] - rpix * p$mgp[2] , yy[2], anchor="e",
text=as.character(tmp[i]), fill = p$col.axis, font=fnt.axis)
}
## Points and labels
## The following 'inherits' works with ordipointlabel, but not
## with zooming
if (inherits(x, "orditkplot")) {
lsco <- scores(x, "labels")
laboff <- rep(0, nrow(lsco))
lsco <- lsco[rownames(sco),]
} else {
lsco <- sco
laboff <- round(p2p * p$ps/2 + diam + 1)
}
pola <- tcltk::tclArray() # points
labtext <- tcltk::tclArray() # text
id <- tcltk::tclArray() # index
for (i in 1:nrow(sco)) {
xy <- usr2xy(sco[i,])
item <- Point(xy[1], xy[2], pch = pch[i], col = pcol[i],
fill = pbg[i], diam = diam[i])
xy <- usr2xy(lsco[i,])
fnt <- c(labfam[i], labsize[i], saneslant(labfnt[i]))
lab <- tcltk::tkcreate(can, "text", xy[1], xy[2]-laboff[i], text=labs[i],
fill = tcol[i], font=fnt)
tcltk::tkaddtag(can, "point", "withtag", item)
tcltk::tkaddtag(can, "label", "withtag", lab)
pola[[lab]] <- item
labtext[[lab]] <- labs[i]
id[[lab]] <- i
}
##############################
### Mouse operations on canvas
##############################
## Plotting and Moving
## Mouse enters a label
pEnter <- function() {
tcltk::tkdelete(can, "box")
hbox <- tcltk::tkcreate(can, "rectangle",
tcltk::tkbbox(can, "current"),
outline = "red", fill = "yellow")
tcltk::tkaddtag(can, "box", "withtag", hbox)
tcltk::tkitemraise(can, "current")
}
## Mouse leaves a label
pLeave <- function() {
tcltk::tkdelete(can, "box")
}
## Select label
pDown <- function(x, y) {
x <- as.numeric(x)
y <- as.numeric(y)
tcltk::tkdtag(can, "selected")
tcltk::tkaddtag(can, "selected", "withtag", "current")
tcltk::tkitemraise(can, "current")
p <- as.numeric(tcltk::tkcoords(can,
pola[[tcltk::tkfind(can, "withtag", "current")]]))
.pX <<- (p[1]+p[3])/2
.pY <<- (p[2]+p[4])/2
.lastX <<- x
.lastY <<- y
}
## Move label
pMove <- function(x, y) {
x <- as.numeric(x)
y <- as.numeric(y)
tcltk::tkmove(can, "selected", x - .lastX, y - .lastY)
tcltk::tkdelete(can, "ptr")
tcltk::tkdelete(can, "box")
.lastX <<- x
.lastY <<- y
## xadj,yadj: adjust for canvas scrolling
xadj <- as.numeric(tcltk::tkcanvasx(can, 0))
yadj <- as.numeric(tcltk::tkcanvasy(can, 0))
hbox <- tcltk::tkcreate(can, "rectangle",
tcltk::tkbbox(can, "selected"),
outline = "red")
tcltk::tkaddtag(can, "box", "withtag", hbox)
conn <- tcltk::tkcreate(can, "line", .lastX + xadj, .lastY+yadj,
.pX, .pY, fill="red")
tcltk::tkaddtag(can, "ptr", "withtag", conn)
}
## Edit label
pEdit <- function() {
tcltk::tkdtag(can, "selected")
tcltk::tkaddtag(can, "selected", "withtag", "current")
tcltk::tkitemraise(can, "current")
click <- tcltk::tkfind(can, "withtag", "current")
txt <- tcltk::tclVar(labtext[[click]])
i <- as.numeric(id[[click]])
tt <- tcltk::tktoplevel()
labEd <- tcltk::tkentry(tt, width=20, textvariable=txt)
tcltk::tkgrid(tcltk::tklabel(tt, text = "Edit label"))
tcltk::tkgrid(labEd, pady="5m", padx="5m")
isDone <- function() {
txt <- tcltk::tclvalue(txt)
tcltk::tkitemconfigure(can, click, text = txt)
rownames(sco)[i] <<- txt
tcltk::tkdestroy(tt)
}
tcltk::tkbind(labEd, "<Return>", isDone)
}
## Zooming: draw rectangle and take its user coordinates
## Rectangle: first corner
pRect0 <- function(x, y) {
x <- as.numeric(x)
y <- as.numeric(y)
## yadj here and below adjusts for canvas scrolling
yadj <- as.numeric(tcltk::tkcanvasy(can, 0))
.pX <<- x
.pY <<- y + yadj
}
## Grow rectangle
pRect <- function(x, y) {
x <- as.numeric(x)
y <- as.numeric(y)
tcltk::tkdelete(can, "box")
yadj <- as.numeric(tcltk::tkcanvasy(can, 0))
.lastX <<- x
.lastY <<- y + yadj
rect <- tcltk::tkcreate(can, "rectangle", .pX, .pY, .lastX, .lastY,
outline="blue")
tcltk::tkaddtag(can, "box", "withtag", rect)
}
## Redraw ordiktplot with new xlim and ylim
pZoom <- function() {
nxlim <- sort(c(x2usr(.pX), x2usr(.lastX)))
nylim <- sort(c(y2usr(.pY), y2usr(.lastY)))
xy <- ordDump()
## Move labels closer to points in zoom
## FIXME: Doesn't do a perfect job
mul <- abs(diff(nxlim)/diff(xlim))
xy$labels <- xy$points + (xy$labels - xy$points)*mul
xy$args$xlim <- nxlim
xy$args$ylim <- nylim
orditkplot(xy)
}
## Dummy location of the mouse
.lastX <- 0
.lastY <- 0
.pX <- 0
.pY <- 0
## Mouse bindings:
## Moving a label
tcltk::tkitembind(can, "label", "<Any-Enter>", pEnter)
tcltk::tkitembind(can, "label", "<Any-Leave>", pLeave)
tcltk::tkitembind(can, "label", "<1>", pDown)
tcltk::tkitembind(can, "label", "<ButtonRelease-1>",
function() {tcltk::tkdtag(can, "selected")
tcltk::tkdelete(can, "ptr")})
tcltk::tkitembind(can, "label", "<B1-Motion>", pMove)
## Edit labels
tcltk::tkitembind(can, "label", "<Double-Button-1>", pEdit)
## Zoom (with one-button mouse)
tcltk::tkbind(can, "<Shift-Button-1>", pRect0)
tcltk::tkbind(can, "<Shift-B1-Motion>", pRect)
tcltk::tkbind(can, "<Shift-ButtonRelease>", pZoom)
## Zoom (with right button)
tcltk::tkbind(can, "<Button-3>", pRect0)
tcltk::tkbind(can, "<B3-Motion>", pRect)
tcltk::tkbind(can, "<ButtonRelease-3>", pZoom)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/orditkplot.R
|
`orditorp` <-
function (x, display, labels, choices = c(1, 2), priority, select,
cex = 0.7, pcex, col = par("col"),
pcol, pch = par("pch"), air = 1, ...)
{
if (missing(pcex))
pcex <- cex
if (missing(pcol))
pcol <- col
x <- scores(x, display = display, choices = choices, ...)
kk <- complete.cases(x)
if (missing(labels))
labels <- rownames(x)
if (missing(priority))
priority <- rowSums((scale(x)^2))
if (!missing(select)) {
x <- .checkSelect(select, x)
labels <- .checkSelect(select, labels)
priority <- .checkSelect(select, priority)
kk <- .checkSelect(select, kk)
}
## remove NA scores
x <- x[kk,]
priority <- priority[kk]
labels <- labels[kk]
w <- abs(strwidth(labels, cex = cex))/2 * air
h <- abs(strheight(labels, cex = cex))/2 * air
xx <- cbind(x[, 1] - w, x[, 1] + w, x[, 2] - h, x[, 2] +
h)
is.na(priority) <- w == 0
ord <- rev(order(priority, na.last = FALSE))
xx <- xx[ord, ]
x <- x[ord, ]
labels <- labels[ord]
tt <- logical(nrow(xx))
tt[1] <- TRUE
for (i in 2:(nrow(xx) - sum(is.na(priority)))) {
j <- 1:(i - 1)
j <- j[tt[j]]
tt[i] <- all(xx[i, 1] > xx[j, 2] | xx[j, 1] > xx[i, 2] |
xx[i, 3] > xx[j, 4] | xx[j, 3] > xx[i, 4])
}
if (sum(!tt)) {
if (length(pch) > 1)
pch <- (pch[ord])[!tt]
if (length(pcex) > 1)
pcex <- (pcex[ord])[!tt]
if (length(pcol) > 1)
pcol <- (pcol[ord])[!tt]
ordiArgAbsorber(x[!tt, , drop = FALSE], pch = pch, cex = pcex,
col = pcol, FUN = points, ...)
}
if (length(cex) > 1)
cex <- (cex[ord])[tt]
if (length(col) > 1)
col <- (col[ord])[tt]
ordiArgAbsorber(x[tt, , drop = FALSE], labels = labels[tt], cex = cex,
col = col, FUN = text, ...)
names(tt) <- labels
invisible(tt[order(ord)])
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/orditorp.R
|
`ordixyplot` <-
function(x, data = NULL, formula, display = "sites", choices=1:3,
panel = "panel.ordi", aspect = "iso", envfit,
type = c("p", "biplot"), ...)
{
localXyplot <- function(..., shrink, origin, scaling) xyplot(...)
p <- as.data.frame(scores(x, display = display, choices = choices, ...))
if (!is.null(data))
p <- cbind(p, data)
if (missing(formula)) {
v <- colnames(p)
formula <- as.formula(paste(v[2], "~", v[1]))
}
if ("biplot" %in% type && ((!is.null(x$CCA) && x$CCA$rank > 0) ||
!missing(envfit))) {
if (missing(envfit))
envfit <- NULL
env <- ordilattice.getEnvfit(formula, x, envfit, choices, ...)
if (!is.null(env$arrows)) {
mul <- apply(p[,colnames(env$arrows)], 2, range)/apply(env$arrows, 2, range)
mul <- min(mul[is.finite(mul) & mul > 0])
env$arrows <- mul * env$arrows
}
} else {
env <- NULL
}
## plot polygon for all data plus superpose polygons for each panel
if ("polygon" %in% type) {
pol <- p[, all.vars(formula)[2:1]]
pol <- pol[chull(pol),]
} else {
pol <- NULL
}
localXyplot(formula, data = p, panel = panel, aspect = aspect,
biplot = env, polygon = pol, type = type, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/ordixyplot.R
|
panel.ordi <-
function(x, y, biplot, polygon, type = type, ...)
{
tp <- trellis.par.get()
sp <- tp$superpose.symbol
ps <- tp$plot.symbol
## ordixyplot passes polygon of all points, but ordisplom does not
if ("polygon" %in% type && !missing(polygon)) {
ppar <- tp$plot.polygon
lpolygon(polygon, col = ppar$col, border = ppar$border,
alpha = ppar$alpha, lty = ppar$lty, lwd = ppar$lwd, ...)
inpol <- chull(x, y)
par <- tp$superpose.polygon
lpolygon(x[inpol], y[inpol], col = par$col[1L], border = par$border[1L],
alpha = par$alpha[1L], lty = par$lty[1L], lwd = par$lwd[1L], ...)
}
panel.xyplot(x, y, type = type, ...)
if ("biplot" %in% type && !is.null(biplot$arrows)) {
panel.arrows(0, 0, biplot$arrows[,2], biplot$arrows[,1],
col=sp$col, ...)
}
if ("biplot" %in% type && !is.null(biplot$centres)) {
panel.xyplot(biplot$centres[,2], biplot$centres[,1],
col = ps$col,
pch = "+", cex = 3*ps$cex, lwd=2,
...)
}
if ("arrows" %in% type) {
panel.superpose(x, y, panel.groups= "panel.ordiarrows", ...)
}
panel.abline(h=0, lty = 3)
panel.abline(v=0, lty = 3)
}
## needed for "arrows" %in% type
panel.ordiarrows <-
function(x, y, subscripts,
ends = "last", type = "open", length = 0.25, angle = 30, code = 2,
...)
{
n <- length(x)
col <- trellis.par.get("superpose.line")$col
group <- list(...)$group.number
if (is.null(group))
col <- col[1]
else
col = rep(col, len=group)[group]
panel.arrows(x[-n], y[-n], x[-1], y[-1], ends = ends, type = "open",
length = length, angle = angle, code = code,
col = col,
lwd = trellis.par.get("superpose.line")$lwd,
)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/panel.ordi.R
|
`panel.ordi3d` <-
function(x, y, z, aspect, ...)
{
dx <- diff(range(x))
dy <- diff(range(y))
dz <- diff(range(z))
aspect <- c(dy/dx, dz/dx)
panel.cloud(x = x, y = y, z = z, aspect = aspect, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/panel.ordi3d.R
|
`pasteCall` <- function (call, prefix = "Call:")
{
call.str <- paste(deparse(call), collapse = " ")
paste(prefix, call.str, "\n", sep = " ")
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/pasteCall.R
|
`pcnm` <- function(dis, threshold, w, dist.ret = FALSE) {
## square matrix to dist
if ((is.matrix(dis) || is.data.frame(dis)) &&
isSymmetric(unname(as.matrix(dis))))
dis <- as.dist(dis)
if (!inherits(dis, "dist"))
stop("'dis' does not appear to be distances")
if (missing(threshold)) {
threshold <- max(spantree(dis)$dist)
}
dis[dis > threshold] <- 4*threshold
## vegan:::wcmdscale is able to use weights which also means that
## 'k' need not be given, but all vecctors with >0 eigenvalues
## will be found
mypcnm <- wcmdscale(dis, eig = TRUE, w=w)
res <- list(vectors = mypcnm$points, values = mypcnm$eig,
weights = mypcnm$weig)
k <- ncol(mypcnm$points)
res$vectors <- sweep(res$vectors, 2, sqrt(res$values[seq_len(k)]), "/")
if (NCOL(res$vectors))
colnames(res$vectors) <- paste("PCNM", 1:k, sep="")
res$threshold <- threshold
if (dist.ret) {
attr(dis, "method") <- paste(attr(dis, "method"), "pcnm")
attr(dis, "threshold") <- threshold
res$dist <- dis
}
class(res) <- "pcnm"
res
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/pcnm.R
|
## permatfull function
`permatfull` <-
function(m, fixedmar="both", shuffle="both",
strata=NULL, mtype="count", times=99, ...)
{
mtype <- match.arg(mtype, c("prab", "count"))
shuffle <- match.arg(shuffle, c("ind", "samp", "both"))
fixedmar <- match.arg(fixedmar, c("none", "rows", "columns", "both"))
m <- as.matrix(m)
str <- if (is.null(strata))
1 else as.integer(as.factor(strata)[drop = TRUE])
levstr <- unique(str)
nstr <- length(unique(str))
if (!is.null(strata) && any(table(str) < 2))
stop("strata should contain at least two observations")
ALGO <- switch(fixedmar,
"none" = "r00",
"rows" = "r0",
"columns" = "c0",
"both" = ifelse(mtype=="prab", "quasiswap", "r2dtable"))
if (mtype=="count") {
if (fixedmar!="both")
ALGO <- paste(ALGO, shuffle, sep="_")
}
if (is.null(strata)) {
tmp <- simulate(nullmodel(m, ALGO), nsim=times, ...)
perm <- vector("list", times)
for (i in seq_len(times))
perm[[i]] <- tmp[,,i]
} else {
perm <- vector("list", times)
tmp <- vector("list", length(unique(strata)))
for (j in seq_len(nstr)) {
tmp[[j]] <- simulate(nullmodel(m[strata==levstr[j],], ALGO),
nsim=times, ...)
}
for (i in seq_len(times)) {
perm[[i]] <- array(0, dim(m))
for (j in seq_len(nstr)) {
perm[[i]][strata==levstr[j],] <- tmp[[j]][,,i]
}
}
}
if (fixedmar == "both")
shuffle <- NA
if (mtype == "prab")
m <- ifelse(m > 0, 1, 0)
out <- list(call=match.call(), orig=m, perm=perm)
attr(out, "mtype") <- mtype
attr(out, "ptype") <- "full"
attr(out, "method") <- ALGO
attr(out, "fixedmar") <- fixedmar
attr(out, "times") <- times
attr(out, "shuffle") <- shuffle
attr(out, "is.strat") <- !is.null(strata)
attr(out, "strata") <- str
attr(out, "burnin") <- NA
attr(out, "thin") <- NA
class(out) <- c("permatfull", "permat")
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/permatfull.R
|
## permatswap function
`permatswap` <-
function(m, method="quasiswap", fixedmar="both", shuffle="both", strata=NULL,
mtype="count", times=99, burnin = 0, thin = 1, ...)
{
mtype <- match.arg(mtype, c("prab", "count"))
fixedmar <- match.arg(fixedmar, c("rows", "columns", "both"))
shuffle <- match.arg(shuffle, c("samp", "both"))
count <- mtype == "count"
m <- as.matrix(m)
str <- if (is.null(strata))
1 else as.integer(as.factor(strata)[drop = TRUE])
levstr <- unique(str)
nstr <- length(unique(str))
if (!is.null(strata) && any(table(str) < 2))
stop("strata should contain at least two observations")
## evaluating algo type
if (count) {
method <- match.arg(method, c("swap", "quasiswap", "swsh", "abuswap"))
if (method == "swap") {
warning("quantitative swap method may not yield random null models, use only to study its properties")
isSeq <- TRUE
if (fixedmar != "both")
stop("if 'method=\"swap\"', 'fixedmar' must be \"both\"")
} else {
if (method == "abuswap") {
if (fixedmar == "both")
stop("if 'method=\"abuswap\"', 'fixedmar' must not be \"both\"")
direct <- if (fixedmar == "columns")
0 else 1
isSeq <- TRUE
} else {
isSeq <- FALSE
if (method != "swsh" && fixedmar != "both")
stop("'fixedmar' must be \"both\"")
}
}
if (method %in% c("swap", "quasiswap"))
ALGO <- paste(method, "count", sep="_")
if (method == "abuswap")
ALGO <- paste(method, substr(fixedmar, 1, 1), sep="_")
if (method == "swsh") {
if (fixedmar=="both")
stop("if 'method=\"swsh\"', 'fixedmar' must not be \"both\"")
ALGO <- if (fixedmar=="none") {
paste(method, shuffle, sep="_")
} else {
paste(method, shuffle, substr(fixedmar, 1, 1), sep="_")
}
}
} else {
if (fixedmar != "both")
stop("if 'mtype=\"prab\"', 'fixedmar' must be \"both\"")
method <- match.arg(method, c("swap", "quasiswap", "tswap", "backtracking"))
isSeq <- method != "quasiswap"
ALGO <- method
}
if (is.null(strata)) {
tmp <- simulate(nullmodel(m, ALGO),
nsim=times, burnin=burnin, thin=thin, ...)
perm <- vector("list", times)
for (i in seq_len(times))
perm[[i]] <- tmp[,,i]
} else {
perm <- vector("list", times)
tmp <- vector("list", length(unique(strata)))
for (j in seq_len(nstr)) {
tmp[[j]] <- simulate(nullmodel(m[strata==levstr[j],], ALGO),
nsim=times, burnin=burnin, thin=thin, ...)
}
for (i in seq_len(times)) {
perm[[i]] <- array(0, dim(m))
for (j in seq_len(nstr)) {
perm[[i]][strata==levstr[j],] <- tmp[[j]][,,i]
}
}
}
if (mtype == "prab")
m <- ifelse(m > 0, 1, 0)
out <- list(call=match.call(), orig=m, perm=perm)
attr(out, "mtype") <- mtype
attr(out, "ptype") <- "swap"
attr(out, "method") <- ALGO
attr(out, "fixedmar") <- if (method == "swsh") "none" else fixedmar
attr(out, "times") <- times
attr(out, "shuffle") <- if (method == "swsh") shuffle else NA
attr(out, "is.strat") <- !is.null(strata)
attr(out, "strata") <- str
attr(out, "burnin") <- burnin
attr(out, "thin") <- thin
class(out) <- c("permatswap", "permat")
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/permatswap.R
|
### Functions to extract permutation statististic or null model
### results from various vegan objects.
## extract items as 'statistic' and 'permutations'. Specific methods
## towards the end of this file
`permustats` <-
function(x, ...)
{
UseMethod("permustats")
}
## something like str()
`print.permustats` <-
function(x, ...)
{
print(str(x))
invisible(x)
}
### modelled after print.oecosimu (should perhaps have oecosimu() args
### like 'alternative'
`summary.permustats` <-
function(object, interval = 0.95, alternative, ...)
{
TAB <- c("two.sided", "greater", "less")
if (missing(alternative))
alt <- TAB[match(object$alternative, TAB)]
else
alt <- match.arg(alternative, TAB, several.ok = TRUE)
if (any(is.na(alt)))
stop("alternative missing")
nstat <- length(object$statistic)
nalt <- length(alt)
## Replicate alternative to length of statistic
if ((nalt < nstat) && identical(nalt, 1L)) {
alt <- rep(alt, length.out = nstat)
}
compint <- (1 - interval) / 2
PROBS <- list(two.sided = c(compint, 0.5, interval + compint),
greater = c(NA, 0.5, interval),
less = c(1 - interval, 0.5, NA))
probs <- PROBS[alt]
## take care that permutations are in a column matrix
permutations <- as.matrix(object$permutations)
object$means <- colMeans(permutations)
sd <- apply(permutations, 2, sd)
object$z <-
(object$statistic - object$means)/sd
qFun <- function(i, sim, probs) {
quantile(sim[, i], probs = probs[[i]], na.rm = TRUE)
}
object$quantile <- lapply(seq_along(probs), qFun, sim = permutations, probs = probs)
object$quantile <- do.call("rbind", object$quantile)
dimnames(object$quantile) <- list(NULL, c("lower", "median", "upper"))
object$interval <- interval
## P-values
if (is.integer(object$statistic) && is.integer(permutations)) {
pless <- rowSums(object$statistic >= t(permutations), na.rm = TRUE)
pmore <- rowSums(object$statistic <= t(permutations), na.rm = TRUE)
} else {
EPS <- sqrt(.Machine$double.eps)
pless <- rowSums(object$statistic + EPS >= t(permutations),
na.rm = TRUE)
pmore <- rowSums(object$statistic - EPS <= t(permutations),
na.rm = TRUE)
}
nsimul <- nrow(permutations)
if (any(is.na(permutations))) {
warning("some simulated values were NA and were removed")
nsimul <- nsimul - colSums(is.na(permutations))
}
p <- rep(NA, length(object$statistic))
for(i in seq_along(p))
p[i] <- switch(alt[i],
two.sided = 2*pmin(pless[i], pmore[i]),
greater = pmore[i],
less = pless[i])
object$p <- pmin(1, (p + 1)/(nsimul + 1))
## out
class(object) <- "summary.permustats"
object
}
`print.summary.permustats` <- function(x, ...) {
m <- cbind("statistic" = x$statistic,
"SES" = x$z,
"mean" = x$means,
x$quantile,
"Pr(perm)" = x$p)
cat("\n")
printCoefmat(m, tst.ind = 1:(ncol(m)-1), na.print = "", ...)
writeLines(strwrap(paste0("(Interval (Upper - Lower) = ", x$interval, ")", sep = ""),
initial = "\n"))
invisible(x)
}
### combine permustats objects. Function checks that statistic field
### is equal (name, value) before proceeding, sees if the alternative
### is equal, and then combines permutations.
`c.permustats` <-
function(..., recursive = FALSE)
{
mods <- list(...)
## check stats
stats <- lapply(mods, function(z) z$statistic)
if (!all(sapply(stats[-1], function(z) identical(stats[[1]], z))))
stop("statistics are not equal")
stats <- stats[[1]]
## check alternative
alt <- lapply(mods, function(z) z$alternative)
if (all(sapply(alt[-1], function(z) identical(alt[[1]], z))))
alt <- alt[[1]]
else
alt <- NA
## combine permutations
p <- do.call(rbind, lapply(mods, function(z) z$permutations))
## return permustats
structure(list(statistic = stats,
permutations = p,
alternative = alt),
class = "permustats")
}
### densityplot
`densityplot.permustats` <-
function(x, data, xlab = "Permutations", ...)
{
obs <- x$statistic
sim <- rbind(x$statistic, as.matrix(x$permutations))
nm <- names(obs)[col(sim)]
densityplot( ~ as.vector(sim) | factor(nm, levels = unique(nm)),
xlab = xlab,
panel = function(x, ...) {
panel.densityplot(x, ...)
panel.abline(v = obs[panel.number()], ...)
},
...)
}
### simple density: normally densityplot should be used (or I suggest
### so), but we also offer basic density. This can be either with or
### without observed statistic.
`density.permustats` <-
function(x, observed = TRUE, ...)
{
## only works with statistic
if (length(x$statistic) > 1)
stop(gettextf("only works with one statistic: you got %d",
length(x$statistic)))
p <- x$permutations
if (observed)
p <- c(x$statistic, p)
out <- density(p)
out$call <- match.call()
out$call[[1]] <- as.name("density")
out
}
### QQ-plot against Guaussian distribution
`qqnorm.permustats` <-
function(y, observed = TRUE, ...)
{
## only works with statistic
if (length(y$statistic) > 1)
stop(gettextf("only works with one statistic: you got %d",
length(y$statistic)))
p <- y$permutations
if (observed)
p <- c(y$statistic, p)
q <- qqnorm(p, ...)
if (observed)
abline(h = y$statistic, ...)
invisible(q)
}
`qqmath.permustats` <-
function(x, data, observed = TRUE, sd.scale = FALSE,
ylab = "Permutations", ...)
{
## sd.scale: standardize before use
if (sd.scale) {
x$permutations <- scale(x$permutations)
x$statistic <- (x$statistic - attr(x$permutations, "scaled:center"))/
attr(x$permutations, "scaled:scale")
}
obs <- x$statistic
if (observed)
sim <- rbind(x$statistic, as.matrix(x$permutations))
else
sim <- as.matrix(x$permutations)
nm <- names(obs)[col(sim)]
qqmath( ~ as.vector(sim) | factor(nm, levels = unique(nm)),
ylab = ylab,
panel = function(x, ...) {
panel.qqmath(x, ...)
if (observed)
panel.abline(h = obs[panel.number()], ...)
},
...)
}
## boxplot for (standardized) effect size: permutations are centred to
## the value of statistic, and optionally standardized to equal sd
## w.r.t. to column mean (not to the statistics). This shows the
## effect size, or the deviation from the observed statistic (= 0).
`boxplot.permustats` <-
function(x, scale = FALSE, names, ...)
{
p <- x$permutations
if (isTRUE(scale))
scale <- apply(p, 2, sd, na.rm = TRUE)
p <- scale(p, center = x$statistic, scale = scale)
if (missing(names))
names <- attr(x$statistic, "names")
boxplot(p, names = names, ...)
}
## pairs plot permuted variables against each other
`pairs.permustats` <-
function(x, ...)
{
p <- x$permutations
colnames(p) <- attr(x$statistic, "names")
pairs(p, ...)
}
###
### specific methods to extract permustats
###
`permustats.anosim` <-
function(x, ...)
{
structure(list(
"statistic" = structure(x$statistic, names = "R"),
"permutations" = x$perm,
"alternative" = "greater"),
class = "permustats")
}
`permustats.mantel` <-
function(x, ...)
{
structure(list(
"statistic" = structure(x$statistic, names = "r"),
"permutations" = x$perm,
"alternative" = "greater"),
class = "permustats")
}
`permustats.mrpp` <-
function(x, ...)
{
structure(list(
"statistic" = structure(x$delta, names = "delta"),
"permutations" = x$boot.deltas,
"alternative" = "less"),
class = "permustats")
}
`permustats.oecosimu` <-
function(x, ...)
{
structure(list(
"statistic" = x$oecosimu$statistic,
"permutations" = t(x$oecosimu$simulated),
"alternative" = x$oecosimu$alternative),
class = "permustats")
}
`permustats.ordiareatest` <-
function(x, ...)
{
structure(list(
"statistic" = x$areas,
"permutations" = t(x$permutations),
"alternative" = "less"),
class = "permustats")
}
`permustats.permutest.cca` <-
function(x, ...)
{
structure(list(
"statistic" = structure(x$F.0, names = x$termlabels),
"permutations" = x$F.perm,
"alternative" = "greater"),
class = "permustats")
}
`permustats.protest` <-
function(x, ...)
{
structure(list(
"statistic" = structure(x$t0, names = "r"),
"permutations" = x$t,
"alternative" = "greater"),
class = "permustats")
}
### the following do not return permutation data
`permustats.CCorA` <-
function(x, ...)
{
stop("no permutation data available")
}
`permustats.envfit` <-
function(x, ...)
{
stop("no permutation data available")
}
`permustats.factorfit` <-
function(x, ...)
{
stop("no permutation data available")
}
`permustats.vectorfit` <-
function(x, ...)
{
stop("no permutation data available")
}
`permustats.mso` <-
function(x, ...)
{
stop("no permutation data available")
}
`permustats.permutest.betadisper` <-
function(x, ...)
{
ntypes <- NCOL(x$perm)
alt <- if (ntypes > 1) {
c("greater", rep("two.sided", ntypes - 1))
} else {
"greater"
}
structure(list("statistic" = x$statistic,
"permutations" = x$perm,
"alternative" = alt),
class = "permustats")
}
`permustats.anova.cca` <-
function(x, ...)
{
if (is.null(attr(x, "F.perm")))
stop("no permutation data available")
F.perm <- attr(x, "F.perm")
k <- !is.na(x$F)
F.0 <- x$F[k]
structure(list(
"statistic" = structure(F.0, names = rownames(x)[k]),
"permutations" = F.perm,
"alternative" = "greater"),
class = "permustats")
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/permustats.R
|
`permutest.betadisper` <- function(x, pairwise = FALSE,
permutations = 999,
parallel = getOption("mc.cores"), ...)
{
EPS <- sqrt(.Machine$double.eps) # for P-value comparisons
t.statistic <- function(x, y) {
m <- length(x)
n <- length(y)
xbar <- mean(x)
ybar <- mean(y)
xvar <- var(x)
yvar <- var(y)
pooled <- sqrt(((m-1)*xvar + (n-1)*yvar) / (m+n-2))
(xbar - ybar) / (pooled * sqrt(1/m + 1/n))
}
permFun <- function(idx) {
if (!is.matrix(idx)) {
dim(idx) <- c(1, length(idx))
}
R <- nrow(idx)
Fperm <- matrix(nrow = R, ncol = 1)
if (pairwise) { # set up object to hold t stats
Tperm <- matrix(ncol = n.pairs, nrow = R)
Jseq <- seq_len(n.pairs)
}
rdf <- nobs - p # residual degrees of freedom
## iterate
for (i in seq_len(R)) { # iterate
take <- idx[i, ] # current permutation from set
p.resid <- resids[take] # permute residuals
f <- qr.fitted(mod.Q, p.resid) # create new data
mss <- sum((f - mean(f))^2)
r <- qr.resid(mod.Q, p.resid)
rss <- sum(r^2)
resvar <- rss / rdf
Fperm[i, ] <- (mss / (p - 1)) / resvar
## pairwise tests
if(pairwise) {
for(j in Jseq) {
grp1 <- x$distance[take][group == combin[1, j]]
grp2 <- x$distance[take][group == combin[2, j]]
Tperm[i, j] <- t.statistic(grp1, grp2)
}
}
}
## bind on pairwise stats if any
if (pairwise) {
Fperm <- cbind(Fperm, Tperm)
}
Fperm
}
if(!inherits(x, "betadisper"))
stop("only for class \"betadisper\"")
## will issue error if only a single group
mod.aov <- anova(x)
nobs <- length(x$distances) ## number of observations
mod <- lm(x$distances ~ x$group)
mod.Q <- mod$qr
p <- mod.Q$rank
resids <- qr.resid(mod.Q, x$distances)
## extract groups
group <- x$group
## permutations is either a single number, a how() structure or a
## permutation matrix
permutations <- getPermuteMatrix(permutations, nobs)
nperm <- nrow(permutations)
## pairwise comparisons
if(pairwise) {
combin <- combn(levels(x$group), 2) # unique pairings
n.pairs <- ncol(combin)
}
## Parallel processing of permutations
if (is.null(parallel)) {
parallel <- 1
}
hasClus <- inherits(parallel, "cluster")
if (hasClus || parallel > 1L) {
if (.Platform$OS.type == "unix" && !hasClus) {
Pstats <- do.call("rbind",
mclapply(seq_len(nperm),
function(x) permFun(permutations[x, , drop = FALSE]),
mc.cores = parallel))
} else {
## if hasClus, don't set up and top a temporary cluster
if (!hasClus) {
parallel <- makeCluster(parallel)
}
Pstats <- parApply(parallel, permutations, 1,
function(x) permFun(x))
if (is.null(dim(Pstats))) {
Pstats <- matrix(Pstats) # one-column matrix
} else {
Pstats <- t(Pstats) # transpose statistics to columns
}
if (!hasClus) {
stopCluster(parallel)
}
}
} else {
Pstats <- permFun(permutations)
}
## Process results
F0 <- summary(mod)$fstatistic[1]
Fstats <- Pstats[, 1, drop = TRUE] # allow empty dim to be dropped
statistic <- F0
names(statistic) <- "Overall (F)"
## pairwise comparisons
if(pairwise) {
T0 <- apply(combn(levels(group), 2), 2, function(z) {
t.statistic(x$distances[group == z[1]],
x$distances[group == z[2]])})
Tstats <- Pstats[, -1, drop = FALSE]
statistic <- c(statistic, T0)
}
## compute permutation p-value
pval <- (sum(Fstats >= F0 - EPS) + 1) / (length(Fstats) + 1)
if(pairwise) {
df <- apply(combin, 2, function(z) {
length(x$distances[group == z[1]]) +
length(x$distance[group == z[2]]) - 2})
pairp <- (colSums(sweep(abs(Tstats), 2, abs(T0), '>=')) + 1) /
(NROW(Tstats) + 1)
pairp <- list(observed = 2 * pt(-abs(T0), df),
permuted = pairp)
tnames <- apply(combin, 2, paste, collapse = "-")
names(pairp$observed) <- names(pairp$permuted) <- tnames
names(statistic)[-1] <- paste(tnames, "(t)")
} else {
pairp <- NULL
}
retval <- cbind(mod.aov[, 1:4], c(nperm, NA), c(pval, NA))
dimnames(retval) <- list(c("Groups", "Residuals"),
c("Df", "Sum Sq", "Mean Sq", "F", "N.Perm",
"Pr(>F)"))
retval <- list(tab = retval,
pairwise = pairp,
groups = levels(group),
statistic = statistic,
perm = if (pairwise) {
structure(cbind(Fstats, Tstats), dimnames = list(NULL, names(statistic)))
} else {
structure(Fstats, names = names(statistic))
},
control = attr(permutations, "control"))
class(retval) <- "permutest.betadisper"
retval
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/permutest.betadisper.R
|
permutest <- function(x, ...)
UseMethod("permutest")
permutest.default <- function(x, ...)
stop("no default permutation test defined")
`permutest.cca` <-
function (x, permutations = how(nperm=99),
model = c("reduced", "direct", "full"), by = NULL, first = FALSE,
strata = NULL, parallel = getOption("mc.cores"), ...)
{
## do something sensible with insensible input (no constraints)
if (is.null(x$CCA)) {
sol <- list(call = match.call(), testcall = x$call, model = NA,
F.0 = NA, F.perm = NA, chi = c(0, x$CA$tot.chi),
num = 0, den = x$CA$tot.chi,
df = c(0, nrow(x$CA$u) - max(x$pCCA$QR$rank,0) - 1),
nperm = 0, method = x$method, first = FALSE,
Random.seed = NA)
class(sol) <- "permutest.cca"
return(sol)
}
## compatible arguments?
if (!is.null(by)) {
if (first)
stop("'by' cannot be used with option 'first=TRUE'")
by <- match.arg(by, c("onedf", "terms"))
if (by == "terms" && is.null(x$terminfo))
stop("by='terms' needs a model fitted with a formula")
}
model <- match.arg(model)
## special cases
isCCA <- !inherits(x, "rda") # weighting
isPartial <- !is.null(x$pCCA) # handle conditions
isDB <- inherits(x, c("dbrda")) # only dbrda is distance-based
## C function to get the statististics in one loop
getF <- function(indx, E, Q, QZ, effects, first, isPartial, isDB, q, r)
{
# q is the rank(s) of the effect(s) - 1
# r is the rank of the residual term - 1
if (!is.matrix(indx))
indx <- matrix(indx, nrow = 1)
out <- .Call(do_getF, indx, E, Q, QZ, effects, first, isPartial, isDB)
p <- length(effects)
if (!isPartial && !first)
out[, p + 1] <- Chi.tot - rowSums(out[,seq_len(p), drop=FALSE])
if (p > 1) {
if (by == "terms")
out[, seq_len(p)] <- sweep(out[, seq_len(p), drop = FALSE],
2, q, "/")
out <- cbind(out, sweep(out[,seq_len(p), drop=FALSE], 1,
out[, p + 1] / r, "/"))
}
else
out <- cbind(out, (out[, 1] / q) / (out[, 2] / r))
out
}
## end getF
## wrapper to getF for mcapply
getFmcapply <- function(i, permutations,
E, Q, QZ, effects, first, isPartial, isDB, q, r) {
getF(permutations[i,], E = E, Q = Q, QZ = QZ, effects = effects,
first = first, isPartial = isPartial, isDB = isDB, q = q, r = r)
}
## wrapper to getF for parRapply
getFparRapply <- function(i, E, Q, QZ, effects, first, isPartial, isDB,
q, r) {
getF(i, E = E, Q = Q, QZ = QZ, effects = effects, first = first,
isPartial = isPartial, isDB = isDB, q = q, r = r)
}
## QR decomposition
Q <- x$CCA$QR
if (isPartial) {
QZ <- x$pCCA$QR
} else {
QZ <- NULL
}
## statistics: overall tests
if (first) {
Chi.z <- x$CCA$eig[1]
q <- 1
}
else {
Chi.z <- x$CCA$tot.chi
names(Chi.z) <- "Model"
q <- x$CCA$qrank
}
## effects
if (!is.null(by)) {
partXbar <- ordiYbar(x, "partial")
if (by == "onedf") {
effects <- seq_len(q)
termlabs <-
if (isPartial)
colnames(Q$qr)[effects + x$pCCA$QR$rank]
else
colnames(Q$qr)[effects]
} else { # by = "terms"
ass <- x$terminfo$assign
## ass was introduced in vegan_2.5-0
if (is.null(ass))
stop("update() old ordination result object")
pivot <- Q$pivot
if (isPartial)
pivot <- pivot[pivot > x$pCCA$QR$rank] - x$pCCA$QR$rank
ass <- ass[pivot[seq_len(x$CCA$qrank)]]
effects <- cumsum(rle(ass)$length)
termlabs <- labels(terms(x$terminfo))
if (isPartial)
termlabs <- termlabs[termlabs %in% labels(terms(x))]
termlabs <-termlabs[unique(ass)]
}
q <- diff(c(0, effects)) # d.o.f.
if (isPartial)
effects <- effects + x$pCCA$QR$rank
F.0 <- numeric(length(effects))
for (k in seq_along(effects)) {
fv <- qr.fitted(Q, partXbar, k = effects[k])
F.0[k] <- if (isDB) sum(diag(fv)) else sum(fv^2)
}
}
else {
effects <- 0
termlabs <- "Model"
}
## Set up
Chi.xz <- x$CA$tot.chi
names(Chi.xz) <- "Residual"
r <- nobs(x) - Q$rank - 1
if (model == "full")
Chi.tot <- Chi.xz
else Chi.tot <- Chi.z + Chi.xz
if (is.null(by))
F.0 <- (Chi.z/q)/(Chi.xz/r)
else {
Chi.z <- numeric(length(effects))
for (k in seq_along(effects)) {
fv <- qr.fitted(Q, partXbar, k = effects[k])
Chi.z[k] <- if (isDB) sum(diag(fv)) else sum(fv^2)
}
Chi.z <- diff(c(0, F.0))
F.0 <- Chi.z/q * r/Chi.xz
}
## permutation data
E <- switch(model,
"direct" = ordiYbar(x, "initial"),
"reduced" = ordiYbar(x, "partial"),
"full" = ordiYbar(x, "CA"))
## vegan < 2.5-0 cannot use direct model in partial dbRDA
if (is.null(E) && isDB && isPartial)
stop("'direct' model cannot be used in old partial-dbrda: update() result")
## Save dimensions
N <- nrow(E)
permutations <- getPermuteMatrix(permutations, N, strata = strata)
nperm <- nrow(permutations)
## Parallel processing (similar as in oecosimu)
if (is.null(parallel))
parallel <- 1
hasClus <- inherits(parallel, "cluster")
if (hasClus || parallel > 1) {
if(.Platform$OS.type == "unix" && !hasClus) {
tmp <- do.call(rbind,
mclapply(seq_len(nperm), getFmcapply,
mc.cores = parallel,
permutations = permutations,
E = E, Q = Q, QZ = QZ, effects = effects,
first = first, isPartial = isPartial,
isDB = isDB, q = q, r = r))
} else {
## if hasClus, do not set up and stop a temporary cluster
if (!hasClus) {
parallel <- makeCluster(parallel)
}
tmp <- parRapply(parallel, permutations,
getFparRapply,
E = E, Q = Q, QZ = QZ, effects = effects,
first = first, isPartial = isPartial,
isDB = isDB, q = q, r = r)
tmp <- matrix(tmp, nrow = nperm, byrow = TRUE)
if (!hasClus)
stopCluster(parallel)
}
} else {
tmp <- getF(permutations, E = E, Q = Q, QZ = QZ, effects = effects,
first = first, isPartial = isPartial, isDB = isDB,
q = q, r = r)
}
if ((p <- length(effects)) > 1) {
num <- tmp[,seq_len(p)]
den <- tmp[,p+1]
F.perm <- tmp[, seq_len(p) + p + 1]
} else {
num <- tmp[,1]
den <- tmp[,2]
F.perm <- tmp[,3, drop=FALSE]
}
Call <- match.call()
Call[[1]] <- as.name("permutest")
sol <- list(call = Call, testcall = x$call, model = model,
F.0 = F.0, F.perm = F.perm, chi = c(Chi.z, Chi.xz),
num = num, den = den, df = c(q, r), nperm = nperm,
method = x$method, first = first, termlabels = termlabs)
sol$Random.seed <- attr(permutations, "seed")
sol$control <- attr(permutations, "control")
if (!missing(strata)) {
sol$strata <- deparse(substitute(strata))
sol$stratum.values <- strata
}
class(sol) <- "permutest.cca"
sol
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/permutest.cca.R
|
`persp.renyiaccum` <-
function(x, theta = 220, col = heat.colors(100), zlim, ...)
{
dn <- dimnames(x)
Sites <- seq(along=dn[[1]])
Scale <- seq(along=dn[[2]])
Diversity <- x[,,"mean"]
if (missing(zlim))
zlim <- range(Diversity, 0)
if (length(col) > 1) {
ind <- Diversity
ind <- (ind[-1,-1] + ind[-1,-ncol(ind)] + ind[-nrow(ind),-1] +
ind[-nrow(ind),-ncol(ind)])/4
ind <- round((length(col) - 1) * (ind - min(ind))/diff(range(ind)) + 1)
col <- col[ind]
}
persp(Sites, Scale, Diversity, theta = theta, zlim = zlim, col = col, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/persp.renyiaccum.R
|
persp.tsallisaccum <-
function(x, theta = 220, phi = 15, col = heat.colors(100), zlim, ...)
{
persp.renyiaccum(x, theta = theta, phi = phi, col = col, zlim = zlim, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/persp.tsallisaccum.R
|
`plot.MOStest` <-
function(x, which = c(1,2,3,6), ...)
{
show <- rep(FALSE, 8)
show[which] <- TRUE
if (show[1]) {
X <- x$mod$model$x
Y <- x$mod$y
xx <- seq(min(X), max(X), len=101)
pre <- predict(x$mod, newdata=list(x = xx), se=TRUE)
g <- x$mod$family$linkinv
fv <- g(pre$fit)
hi <- g(pre$fit + 2*pre$se)
lo <- g(pre$fit - 2*pre$se)
plot(X, Y, ...)
matlines(xx, cbind(fv, hi, lo), lty=c(1, 2, 2), lwd=c(2, 1, 1), col=1, ...)
}
if (show[2]) {
## Covariance ellipse for the coefficients
s <- summary(x$mod)
k <- coef(s)[2:3, 1:2]
## Fix level to 0.95 (should be changed to an argument?)
level = 0.95
if (family(x$mod)$family %in% c("poisson", "binomial"))
scale <- sqrt(qchisq(level, 2))
else
scale <- sqrt(2 * qf(level, 2, s$df[2]))
ci <- veganCovEllipse(s$cov.scaled[2:3, 2:3], k[,1], scale)
plot(ci, type="l", lwd=2, xlim=range(ci[,1],0), ylim=range(ci[,2],0), ...)
abline(h=0, lty=2, ...)
par <- x$hump[c("min", "max")]
par[par==0] <- sqrt(.Machine$double.eps)
abline(0, -1/2/par[1], ...)
abline(0, -1/2/par[2], ...)
mul <- qnorm(1 - (1 - level)/2)
segments(k[1,1] - k[1,2]*mul, k[2,1], k[1,1]+k[1,2]*mul, k[2,1], lty=3)
segments(k[1,1], k[2,1]-k[2,2]*mul, k[1,1], k[2,1]+k[2,2]*mul, lty=3)
}
if (any(show[-c(1,2)])) {
still <- which(show[-c(1,2)])
plot(x$mod, which = still, ...)
}
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.MOStest.R
|
"plot.anosim" <-
function (x, title=NULL, ...)
{
boxplot(x$dis.rank ~ x$class.vec, notch=TRUE, varwidth=TRUE,
...)
title(title)
if (x$permutations) {
pval <- format.pval(x$signif)
} else {
pval <- "not assessed"
}
mtext(paste("R = ", round(x$statistic, 3), ", ",
"P = ", pval ), 3)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.anosim.R
|
`plot.betadisper` <- function(x, axes = c(1,2), cex = 0.7, pch = seq_len(ng),
col = NULL, lty = "solid", lwd = 1, hull = TRUE,
ellipse = FALSE, conf,
segments = TRUE, seg.col = "grey",
seg.lty = lty, seg.lwd = lwd,
label = TRUE, label.cex = 1,
ylab, xlab, main, sub, ...)
{
localAxis <- function(..., col, bg, pch, cex, lty, lwd) axis(...)
localBox <- function(..., col, bg, pch, cex, lty, lwd) box(...)
localTitle <- function(..., col, bg, pch, cex, lty, lwd) title(...)
Ellipse <- function(scrs, centres, conf, col, lty, lwd, ...) {
mat <- cov.wt(scrs, center = centres)
if (mat$n.obs == 1)
mat$cov[] <- 0
xy <- if (mat$n.obs > 1) {
veganCovEllipse(mat$cov, mat$center, conf)
} else {
scrs
}
ordiArgAbsorber(xy, FUN = lines, col = col, lty = lty, lwd = lwd, ...)
}
if(missing(main))
main <- deparse(substitute(x))
if(missing(sub))
sub <- paste("method = \"", attr(x, "method"), "\"", sep = "")
if(missing(xlab))
xlab <- paste("PCoA", axes[1])
if(missing(ylab))
ylab <- paste("PCoA", axes[2])
t <- if (missing(conf)) {
1
} else {
sqrt(qchisq(conf, df = 2))
}
g <- scores(x, choices = axes)
ng <- length(levels(x$group))
lev <- levels(x$group)
## sort out colour vector if none supplied
if (is.null(col)) {
col <- palette()
}
col <- rep_len(col, ng) # make sure there are enough colors
seg.col <- rep_len(seg.col, ng) # ditto for segments
plot(g$sites, asp = 1, type = "n", axes = FALSE, ann = FALSE, ...)
## if more than 1 group level
if(is.matrix(g$centroids)) {
for(i in seq_along(lev)) {
curlev <- lev[i]
take <- x$group == curlev
j <- which(lev == curlev)
if (segments) {
segments(g$centroids[j, 1L], g$centroids[j, 2L],
g$sites[take, 1L],
g$sites[take, 2L], col = seg.col[i], lty = seg.lty,
lwd = seg.lwd)
}
if(hull) {
ch <- chull(g$sites[take,, drop=FALSE])
ch <- c(ch, ch[1])
lines(x$vectors[take, axes, drop=FALSE][ch, ],
col = col[i], lty = lty, lwd = lwd, ...)
}
if (ellipse) {
Ellipse(g$sites[take, , drop = FALSE],
centres = g$centroids[j, ],
conf = t,
col = col[i], lty = lty, lwd = lwd, ...)
}
points(g$centroids[j, , drop = FALSE], pch = 16, cex = 1,
col = col[i], ...)
}
} else {
## single group
if (segments) {
segments(g$centroids[, 1L], g$centroids[, 2L],
g$sites[, 1L], g$sites[, 2L], col = seg.col,
lty = seg.lty, ...)
}
if(hull) {
ch <- chull(g$sites)
ch <- c(ch, ch[1])
lines(x$vectors[, axes][ch, ], col = col[1L], lty = lty,
lwd = lwd, ...)
}
if (ellipse) {
Ellipse(g$sites,
centres = g$centroids,
conf = t,
col = col[1L], lty = lty, lwd = lwd,...)
}
points(g$centroids[, 1L], g$centroids[, 2L],
pch = 16, cex = 1, col = col[1L], ...)
}
points(g$sites, pch = pch[x$group], cex = cex, col = col[x$group], ...)
if (label) {
ordilabel(x, display = "centroids", choices = axes, cex = label.cex,
col = col)
}
localTitle(main = main, xlab = xlab, ylab = ylab, sub = sub, ...)
localAxis(1, ...)
localAxis(2, ...)
localBox(...)
class(g) <- "ordiplot"
invisible(g)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.betadisper.R
|
`plot.betadiver` <-
function (x, ...)
{
xy <- scores(x, ...)
plot(c(0, 1), c(0, sqrt(0.75)), type = "n", axes = FALSE,
xlab = "", ylab = "", asp = 1)
for (tic in seq(0.2, 0.8, by = 0.2)) {
segments(tic, 0, tic/2, sqrt(0.75) * tic, lty = 3)
segments(tic/2, sqrt(0.75) * tic, 1 - tic/2, sqrt(0.75) *
tic, lty = 3)
segments(tic, 0, tic/2 + 0.5, sqrt(0.75) * (1 - tic),
lty = 3)
}
text(c(0, 1, 0.5), c(0, 0, sqrt(0.75)), c("b'", "c'", "a'"),
pos = c(2, 4, 3), cex = par("cex.axis"), xpd=TRUE)
lines(c(0, 1, 0.5, 0), c(0, 0, sqrt(0.75), 0), xpd = TRUE)
points(xy, ...)
class(xy) <- "ordiplot"
invisible(xy)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.betadiver.R
|
`plot.cascadeKM` <-
function (x, min.g, max.g, grpmts.plot = TRUE, sortg = FALSE,
gridcol = NA, ...)
{
wrapres <- x
number <- (as.numeric(gsub(" groups", "", colnames(wrapres$results))))
if (missing(min.g))
min.g <- min(number)
if (missing(max.g))
max.g <- max(number)
if (min.g < 2)
min.g = 2
c.min <- which(number == min.g)
c.max <- which(number == max.g)
if (length(c.min) == 0) {
stop("min.g value given has not been calculated by 'cascadeKM'\n")
}
if (length(c.max) == 0) {
stop("max.g value given has not been calculated by 'cascadeKM'\n")
}
x <- wrapres$partition[, c.min:c.max]
w <- wrapres$results[2, c.min:c.max]
criterion <- wrapres$criterion
x <- pregraphKM(x)
if (sortg) {
x <- orderingKM(x)
}
main = (paste("K-means partitions comparison"))
xlab = ("Number of groups in each partition")
ylab = ("Objects")
nc = ncol(x)
colo <- (rainbow(max.g + 1))
if (grpmts.plot) {
def.par <- par(no.readonly = TRUE)
nf <- layout(matrix(c(1, 2), 1, 2), widths = c(3, 1),
TRUE)
par(mar = c(5, 5, 5, 1), bg = "white", col = "black")
image(1:nrow(x), 1:nc, x, col = colo, yaxt = "n", frame.plot = TRUE,
main = main, xlab = ylab, ylab = xlab, bg = NA)
grid(nx = nrow(x), ny = max.g - min.g + 1, col = gridcol)
box()
axis(2, seq(min.g - min.g + 1, max.g - min.g + 1, by = 1),
labels = seq(min.g, max.g, by = 1))
axis(1)
par(mar = c(5, 2, 5, 1))
par(bg = "white", fg = "black", col = "black")
plot(y = min.g:max.g, x = w[1:nc], type = "b", main = paste(criterion,
"\ncriterion", sep = ""), ylab = "", ylim = c(min.g -
0.5, max.g + 0.5), yaxs = "i", yaxt = "n", xlab = "Values")
grid(nx = NULL, ny = max.g - min.g + 1, col = gridcol)
box()
axis(2, seq(min.g, max.g, by = 1), labels = seq(min.g, max.g,
by = 1), col.axis = "black")
axis(1)
maxx = which.max(w[])
minx = which.min(w[])
tops <- which(w[c(2:nc)] - w[c(1:(nc - 1))] > 0) + 1
maxx.o <- NA
if (length(tops) != 0) {
if (length(which(tops > maxx)) != 0)
maxx.o <- tops[which(tops > maxx)]
}
tops <- which(w[c(2:nc)] - w[c(1:(nc - 1))] < 0) + 1
minx.o <- NA
if (length(tops) != 0) {
if (length(which(tops > minx)) != 0)
minx.o <- tops[which(tops > minx)]
}
if (tolower(criterion) == "calinski") {
if (!is.na(maxx.o[1]))
points(y = maxx.o + min.g - 1, x = w[maxx.o],
col = "orange", pch = 19)
points(y = maxx + min.g - 1, x = w[maxx], col = "red",
pch = 19)
}
else if (tolower(criterion) == "likelihood") {
if (!is.na(maxx.o[1])) {
points(y = maxx.o + min.g - 1, x = w[maxx.o],
col = "orange", pch = 19)
}
points(y = maxx + min.g - 1, x = w[maxx], col = "red",
pch = 19)
}
else if (tolower(criterion) == "ssi") {
if (!is.na(maxx.o[1])) {
points(y = maxx.o + min.g - 1, x = w[maxx.o],
col = "orange", pch = 19)
}
points(y = maxx + min.g - 1, x = w[maxx], col = "red",
pch = 19)
}
else {
cat("When using the", criterion, "criterion, no red marker is",
"used to indicate the best value.\n")
}
par(def.par)
}
else {
tops <- which(w[c(2:nc)] - w[c(1:(nc - 1))] > 0) + 1
if (length(tops) != 0) {
maxx <- which.max(w[c(2:nc)] - w[c(1:nc - 1)]) +
1
}
else {
maxx <- which.max(w[])
tops = 1
}
}
out <- list(x = x, best.grps = maxx)
if (grpmts.plot)
invisible(out)
else
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.cascadeKM.R
|
`plot.cca` <- function (x, choices = c(1, 2), display = c("sp", "wa", "cn"),
scaling = "species", type, xlim, ylim, const,
correlation = FALSE, hill = FALSE, ...) {
TYPES <- c("text", "points", "none")
## take care that bp arrows are also returned if only cn given
if (any(display %in% c("c","cn")))
display <- c(display, "bp")
g <- scores(x, choices, display, scaling, const, correlation = correlation,
hill = hill, tidy = FALSE)
if (length(g) == 0 || all(is.na(g)))
stop("nothing to plot: requested scores do not exist")
if (!is.list(g))
g <- list(default = g)
## Take care that there are names
for (i in seq_along(g)) {
if (length(dim(g[[i]])) > 1)
rownames(g[[i]]) <- rownames(g[[i]], do.NULL = FALSE,
prefix = substr(names(g)[i], 1, 3))
}
if (!is.null(g$centroids)) {
if (is.null(g$biplot)) # should never be null if g$centroids exist
g$biplot <- scores(x, choices, "bp", scaling)
bipnam <- rownames(g$biplot)
cntnam <- rownames(g$centroids)
g$biplot <- g$biplot[!(bipnam %in% cntnam), , drop = FALSE]
if (nrow(g$biplot) == 0)
g$biplot <- NULL
}
if (missing(type)) {
nitlimit <- 80
nit <- max(nrow(g$spe), nrow(g$sit), nrow(g$con), nrow(g$def))
if (nit > nitlimit)
type <- "points"
else type <- "text"
}
else type <- match.arg(type, TYPES)
## use linestack (and exit) if only one axis was chosen, and
## display includes row or column scores
if (length(choices) == 1) {
## Only one set of scores: plot them
if (length(g) == 1)
pl <- linestack(g[[1]], ...)
## The order of scores is species, sites, constraints, biplot,
## centroids: plot two first in this order, but species scores
## on the left
else {
hasSpec <- names(g)[1] == "species"
ylim <- range(c(g[[1]], g[[2]]), na.rm = TRUE)
pl <- linestack(g[[1]], ylim = ylim,
side = ifelse(hasSpec, "left", "right"), ...)
linestack(g[[2]], ylim = ylim,
side = ifelse(hasSpec, "right","left"),
add = TRUE, ...)
}
return(invisible(pl))
}
if (missing(xlim)) {
xlim <- range(g$species[, 1], g$sites[, 1], g$constraints[, 1],
g$biplot[, 1],
if (length(g$centroids) > 0 && all(is.na(g$centroids))) NA else g$centroids[, 1],
g$default[, 1],
na.rm = TRUE)
}
if (!any(is.finite(xlim)))
stop("no finite scores to plot")
if (missing(ylim)) {
ylim <- range(g$species[, 2], g$sites[, 2], g$constraints[, 2],
g$biplot[, 2],
if (length(g$centroids) > 0 && all(is.na(g$centroids))) NA else g$centroids[, 2],
g$default[, 2],
na.rm = TRUE)
}
plot(g[[1]], xlim = xlim, ylim = ylim, type = "n", asp = 1,
...)
abline(h = 0, lty = 3)
abline(v = 0, lty = 3)
if (!is.null(g$species)) {
if (type == "text")
text(g$species, rownames(g$species), col = "red",
cex = 0.7)
else if (type == "points")
points(g$species, pch = "+", col = "red", cex = 0.7)
}
if (!is.null(g$sites)) {
if (type == "text")
text(g$sites, rownames(g$sites), cex = 0.7)
else if (type == "points")
points(g$sites, pch = 1, cex = 0.7)
}
if (!is.null(g$constraints)) {
if (type == "text")
text(g$constraints, rownames(g$constraints), cex = 0.7,
col = "darkgreen")
else if (type == "points")
points(g$constraints, pch = 2, cex = 0.7, col = "darkgreen")
}
if (!is.null(g$biplot) && nrow(g$biplot) > 0 && type != "none") {
if (length(display) > 1) {
mul <- ordiArrowMul(g$biplot)
}
else mul <- 1
attr(g$biplot, "arrow.mul") <- mul
arrows(0, 0, mul * g$biplot[, 1], mul * g$biplot[, 2],
length = 0.05, col = "blue")
biplabs <- ordiArrowTextXY(mul * g$biplot, rownames(g$biplot))
text(biplabs, rownames(g$biplot), col = "blue")
}
if (!is.null(g$regression) && nrow(g$regression > 0) && type != "none") {
rcol <- "purple4"
if (length(display) > 1) {
mul <- ordiArrowMul(g$regression)
}
else mul <- 1
attr(g$regression, "arrow.mul") <- mul
arrows(0, 0, mul * g$regression[, 1], mul * g$regression[, 2],
length = 0.05, col = rcol)
biplabs <- ordiArrowTextXY(mul * g$regression, rownames(g$regression))
text(biplabs, rownames(g$regression), col = rcol)
}
if (!is.null(g$centroids) && !anyNA(g$centroids) && type !=
"none") {
if (type == "text")
text(g$centroids, rownames(g$centroids), col = "blue")
else if (type == "points")
points(g$centroids, pch = "x", col = "blue")
}
if (!is.null(g$default) && type != "none") {
if (type == "text")
text(g$default, rownames(g$default), cex = 0.7)
else if (type == "points")
points(g$default, pch = 1, cex = 0.7)
}
class(g) <- "ordiplot"
invisible(g)
}
## vegan::plot.rda needed because klaR::plot.rda would be used
## instead if klaR package is loaded
`plot.rda`<-
function(x, ...)
{
## not vegan rda?
if (!("CA" %in% names(x)))
stop(gettextf("%s is not a vegan rda object",
sQuote(deparse(substitute(x)))))
NextMethod("plot", x, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.cca.R
|
plot.clamtest <- function(x, xlab, ylab, main,
pch=21:24, col.points=1:4, col.lines=2:4, lty=1:3,
position="bottomright", ...) {
summ <- summary(x)
glabel <- summ$labels
if (missing(main))
main <- "Species Classification"
if (missing(xlab))
xlab <- paste(glabel[2], "(abundance + 1)")
if (missing(ylab))
ylab <- paste(glabel[1], "(abundance + 1)")
Y <- x[,2]
X <- x[,3]
minval <- summ$minv
## plot the dots
rr <- range(X+1,Y+1)
plot(X+1, Y+1, log = "xy", xaxt = "n", yaxt = "n",
col=col.points[as.integer(x$Classes)],
pch=pch[as.integer(x$Classes)],
xlab=xlab, ylab=ylab, main=main,
xlim=rr, ylim=rr, ...)
axis(1, c(1,10,100,1000,10000))
axis(2, c(1,10,100,1000,10000))
## too rare threshold
Ymin <- minval[[1]][1,2]
Xmin <- minval[[2]][1,1]
lines(rep(Xmin, 2)+1, c(0, 1)+1, col=col.lines[1], lty=lty[1])
lines(c(0, 1)+1, rep(Ymin, 2)+1, col=col.lines[1], lty=lty[1])
tmp <- approx(c(Xmin, 1), c(1, Ymin))
lines(tmp$x+1, tmp$y+1, col=col.lines[1], lty=lty[1])
## Y vs. gen threshold
lines(minval[[1]]+1, col=col.lines[2], lty=lty[2])
## X vs. gen threshold
lines(minval[[2]]+1, col=col.lines[3], lty=lty[3])
if (!is.null(position))
legend(position, col=col.points, pch=pch,
legend=rownames(summ$summary))
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.clamtest.R
|
plot.contribdiv <-
function(x, sub, xlab, ylab, ylim, col, ...) {
y <- x[,c(1,3)]
if (missing(ylab))
ylab <- paste("Diversity components (", attr(x, "index"), ")", sep = "")
if (missing(xlab))
xlab <- "Sites"
if (missing(sub))
sub <- paste("Differentiation coefficient = ", round(attr(x, "diff.coef"),3), sep = "")
if (missing(ylim))
ylim <- c(0, max(y))
if (missing(col))
col <- c("lightgrey", "darkgrey")
matplot(y, type = "n", sub=sub, xlab=xlab, ylab=ylab, axes = FALSE,
bty = "n", ...)
polygon(c(1,1:nrow(y),nrow(y)), c(0,y$gamma,0), col=col[1])
polygon(c(1,1:nrow(y),nrow(y)), c(0,y$alpha,0), col=col[2])
axis(side = 1)
axis(side = 2)
box()
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.contribdiv.R
|
"plot.decorana" <-
function (x, choices = c(1, 2), origin = TRUE, display = c("both",
"sites", "species", "none"), cex = 0.8, cols = c(1, 2), type, xlim, ylim,
...)
{
display <- match.arg(display)
sites <- x$rproj
specs <- x$cproj
if (missing(type)) {
nitlimit <- 120
nit <- 0
if (display == "sites" || display == "both")
nit <- nit + nrow(sites)
if (display == "species" || display == "both")
nit <- nit + nrow(specs)
if (nit > nitlimit)
type <- "points"
else type <- "text"
}
else type <- match.arg(type, c("text", "points", "none"))
if (origin) {
sites <- sweep(x$rproj, 2, x$origin, "-")
specs <- sweep(x$cproj, 2, x$origin, "-")
}
sitnam <- rownames(x$rproj)
spenam <- rownames(x$cproj)
sites <- sites[, choices]
specs <- specs[, choices]
## Use linestack if only one dim was specified (and exit)
if (NCOL(sites) == 1 && NCOL(specs) == 1) {
pl <- linestack(sites,
ylim = range(c(sites, specs), na.rm = TRUE), ...)
linestack(specs, side = "left", add = TRUE, ...)
return(invisible(pl))
}
sp.x <- range(specs[, 1])
sp.y <- range(specs[, 2])
st.x <- range(sites[, 1])
st.y <- range(sites[, 2])
switch(display, both = {
if (missing(xlim)) xlim <- range(sp.x, st.x)
if (missing(ylim)) ylim <- range(sp.y, st.y)
}, sites = {
if (missing(xlim)) xlim <- st.x
if (missing(ylim)) ylim <- st.y
}, species = {
if (missing(xlim)) xlim <- sp.x
if (missing(ylim)) ylim <- sp.y
}, none = {
if (missing(xlim)) xlim <- range(sp.x, st.x)
if (missing(ylim)) ylim <- range(sp.y, st.y)
})
plot(sites, type = "n", xlim = xlim, ylim = ylim, asp = 1,
...)
if (origin) {
abline(h = 0, lty = 3)
abline(v = 0, lty = 3)
}
else {
abline(h = x$origin[choices[2]], lty = 3)
abline(v = x$origin[choices[1]], lty = 3)
}
if (type != "none" && (display == "both" || display == "sites")) {
if (type == "text" && !is.null(sitnam))
text(sites, sitnam, cex = cex, col = cols[1])
else points(sites, cex = cex, col = cols[1])
}
if (type != "none" && (display == "both" || display == "species")) {
if (type == "text" && !is.null(spenam))
text(specs, spenam, cex = cex, col = cols[2])
else points(specs, pch = "+", cex = cex, col = cols[2])
}
out <- list(sites = sites, species = specs)
class(out) <- "ordiplot"
invisible(out)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.decorana.R
|
`plot.envfit` <-
function (x, choices = c(1, 2), labels, arrow.mul, at = c(0, 0),
axis = FALSE, p.max = NULL, col = "blue", bg, add = TRUE, ...)
{
## get labels
labs <- list("v" = rownames(x$vectors$arrows),
"f" = rownames(x$factors$centroids))
## Change labels if user so wishes
if (!missing(labels)) {
## input list of "vectors" and/or "factors"
if (is.list(labels)) {
if (!is.null(labs$v) && !is.null(labels$vectors))
labs$v <- labels$vectors
if (!is.null(labs$f) && !is.null(labels$factors))
labs$f <- labels$factors
} else {
## input vector: either vectors or factors must be NULL,
## and the existing set of labels is replaced
if (!is.null(x$vectors) && !is.null(x$factors))
stop("needs a list with both 'vectors' and 'factors' labels")
## need to handle the case where both sets of labels are NULL
## such as when used with the default interface and single x
if (!is.null(x$factors))
labs$f <- labels
else
labs$v <- labels
}
}
vect <- NULL
if (!is.null(p.max)) {
if (!is.null(x$vectors)) {
take <- x$vectors$pvals <= p.max
x$vectors$arrows <- x$vectors$arrows[take, , drop = FALSE]
labs$v <- labs$v[take]
x$vectors$r <- x$vectors$r[take]
if (nrow(x$vectors$arrows) == 0)
x$vectors <- vect <- NULL
}
if (!is.null(x$factors)) {
tmp <- x$factors$pvals <= p.max
nam <- names(tmp)[tmp]
take <- x$factors$var.id %in% nam
x$factors$centroids <- x$factors$centroids[take,
, drop = FALSE]
labs$f <- labs$f[take]
if (nrow(x$factors$centroids) == 0)
x$factors <- NULL
}
}
if (!is.null(x$vectors)) {
vect <- sqrt(x$vectors$r) * x$vectors$arrows[, choices, drop = FALSE]
if (missing(arrow.mul)) {
if(!add)
arrow.mul <- 1
else
arrow.mul <- ordiArrowMul(vect, at = at)
}
if (axis) {
maxarr <- round(sqrt(max(x$vectors$r)), 1)
ax <- -c(-1, 0, 1) * arrow.mul * maxarr
}
vect <- arrow.mul * vect
vect <- sweep(vect, 2, at, "+")
if (add) {
vtext <- ordiArrowTextXY(vect, labs$v, rescale = FALSE, at = at,
...)
}
}
if (!add) {
plot.new()
## needed for string widths and heights We need dimensions to
## fit completely the names of vectors and factors with no
## clipping at axes. If there are (1) factors and vectors, we
## need to adjust arrow lengths, if there are (2) only factors
## or only vectors, we can use their scores directly. After
## finding the scores, we must expand the scores by string
## widths and heights. The expansion can be only estimated
## after setting plot.window with its xlim and ylim, but we
## need to find xlim and ylim to set the plot.window...
if(is.null(vect) || is.null(x$factors)) {
## Only factors or vectors: set preliminary plot.window
xstack <- rbind(vect, x$factors$centroids)
plot.window(xlim = range(xstack[,1], at[1]),
ylim = range(xstack[,2], at[2]),
asp = 1, ...)
} else {
## Both vectors and factors: set preliminary plot.window
## from factors only and and find arrow.mul (which is
## otherwise ## arrow.mul = 1)
plot.window(xlim = range(x$factors$centroids[,1], at[1]),
ylim = range(x$factors$centroids[,2], at[2]),
asp = 1, ...)
## vfill <- 0.75
arrow.mul <- ordiArrowMul(vect, at = at, fill = 1)
vect <- arrow.mul * vect
}
## Get string dimensions (width/2, height)
sw <- strwidth(c(labs$v, labs$f), ...) / 2
sh <- strheight(c(labs$v, labs$f), ...)
## Reset limits
xstack <- rbind(x$factors$centroids, vect)
xlim <- range(xstack[,1] + sw, xstack[,2] - sw)
ylim <- range(xstack[,2] + sh, xstack[,2] - sh)
plot.window(xlim = xlim, ylim = ylim, asp = 1, ...)
## Re-evaluate arrow.mul, set its text and re-evaluate limits again
if (!is.null(vect)) {
arrow.mul <- ordiArrowMul(vect, at = at, fill = 1)
vect <- arrow.mul * vect
vtext <- ordiArrowTextXY(vect, labs$v, at = at, rescale = FALSE,
...)
sw <- strwidth(labs$v, ...) / 2
sh <- strheight(labs$v, ...)
xlim <- range(xlim, vtext[,1] + sw, vtext[,1] - sw)
ylim <- range(xlim, vtext[,2] + sh, vtext[,2] - sh)
plot.window(xlim = xlim, ylim = ylim, asp = 1, ...)
}
axis(side = 1, ...)
axis(side = 2, ...)
box(...)
alabs <- colnames(vect)
title(..., ylab = alabs[2], xlab = alabs[1])
}
if (!is.null(vect)) {
arrows(at[1], at[2], vect[, 1], vect[, 2], length = 0.05,
col = col)
if (missing(bg))
text(vtext, labs$v, col = col, ...)
else
ordilabel(vtext, labels = labs$v, col = col, fill = bg, ...)
}
if (!is.null(x$factors)) {
if (missing(bg))
text(x$factors$centroids[, choices, drop = FALSE],
labs$f, col = col, ...)
else
ordilabel(x$factors$centroids[, choices, drop = FALSE],
labels = labs$f, col = col, fill = bg, ...)
}
if (axis && !is.null(vect)) {
axis(3, at = ax + at[1], labels = c(maxarr, 0, maxarr),
col = col)
axis(4, at = ax + at[2], labels = c(maxarr, 0, maxarr),
col = col)
}
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.envfit.R
|
"plot.fisherfit" <-
function(x, xlab = "Frequency", ylab = "Species", bar.col = "skyblue",
line.col= "red", lwd=2, ...)
{
freq <- as.numeric(names(x$fisher))
plot(freq, x$fisher, ylab=ylab, xlab=xlab,
ylim=c(0,max(x$fisher)), xlim=c(0.5, max(freq)+0.5), type="n", ...)
rect(freq-0.5,0,freq+0.5,x$fisher, col=bar.col, ...)
alpha <- x$estimate
k <- x$nuisance
curve(alpha*k^x/x, 1, max(freq), col=line.col, lwd=lwd, add=TRUE, ...)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.fisherfit.R
|
`plot.isomap` <-
function (x, net = TRUE, n.col = "gray", type = "points", ...)
{
type <- match.arg(type, c("points", "text", "none"))
if (!net) {
pl <- ordiplot(x, display="sites", type = type, ...)
} else {
pl <- ordiplot(x, display = "sites", type = "none", ...)
z <- scores(pl, "sites")
k <- x$net
## recycle colour for points
n.col <- rep(n.col, length = nrow(z))
n.col <- col2rgb(n.col)/255
## get average of colours of connected points
n.col <- (n.col[,k[,1]] + n.col[,k[,2]])/2
n.col <- rgb(t(n.col))
segments(z[k[,1],1], z[k[,1],2], z[k[,2],1], z[k[,2],2], col=n.col)
if (type == "points")
points(pl, "sites", ...)
else if (type == "text")
ordilabel(pl, ...)
}
invisible(pl)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.isomap.R
|
`plot.mantel.correlog` <-
function(x, alpha=0.05, ...)
{
lim <- max(x$n.tests)
plot(x$mantel.res[1:lim,1],x$mantel.res[1:lim,3],
xlab="Distance class index", ylab="Mantel correlation", pch=22)
if(x$mult == "none") {
signif <- which((x$mantel.res[1:lim,4] <= alpha))
} else {
signif <- which((x$mantel.res[1:lim,5] <= alpha))
}
lines(x$mantel.res[1:lim,1], x$mantel.res[1:lim,3])
points(x$mantel.res[1:lim,1], x$mantel.res[1:lim,3], pch=22, bg="white")
points(x$mantel.res[signif,1], x$mantel.res[signif,3], pch=22, bg="black")
abline(a=0, b=0, col="red")
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.mantel.correlog.R
|
`plot.meandist` <-
function(x, kind = c("dendrogram", "histogram"), cluster = "average", ylim,
axes = TRUE, ...)
{
kind <- match.arg(kind)
n <- attr(x, "n")
if (kind == "dendrogram") {
cl <- hclust(as.dist(x), method = cluster, members = n)
cl <- as.dendrogram(cl, hang = 0)
w <- diag(x)[labels(cl)]
tr <- unlist(dendrapply(cl, function(n) attr(n, "height")))
root <- attr(cl, "height")
if (missing(ylim))
ylim <- range(c(w, tr, root), na.rm = TRUE)
plot(cl, ylim = ylim, leaflab = "none", axes = axes, ...)
seqw <- seq_along(w)
for (i in seqw) {
segments(i, tr[i], i, w[i])
}
pos <- ifelse(w < tr, 1, 3)
pos[is.na(pos)] <- 1
w[is.na(w)] <- tr[is.na(w)]
text(seqw, w, labels = labels(cl), pos = pos, srt = 0, xpd = TRUE, ...)
} else {
w <- diag(x)
seqw <- seq_along(w)
tr <- rep(summary(x)$B, length(w))
if (missing(ylim))
ylim <- range(c(w, tr), na.rm = TRUE)
plot(seqw, tr, ylim = ylim, axes = FALSE, xlab = "", ylab = "",
type = "l", ...)
if (axes)
axis(2, ...)
for (i in seqw) segments(i, tr, i, w[i])
pos <- ifelse(w < tr, 1, 3)
pos[is.na(pos)] <- 1
text(seqw, w, labels = names(n), pos = pos, srt = 0,
xpd = TRUE, ...)
}
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.meandist.R
|
`plot.metaMDS` <-
function (x, display = c("sites","species"), choices = c(1, 2), type = "p",
shrink = FALSE, ...)
{
x <- scores(x, display = display, choices = choices, shrink = shrink)
ordiplot(x, display = display, type = type, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.metaMDS.R
|
### plot() methods for those nested* functions that return sufficient
### data to draw a plot. We display a plot using image() with coloured
### rectangles for occurrences or colours dependent on the
### contribution to the nestedness when appropriate.
`plot.nestedtemp` <-
function (x, kind = c("temperature", "incidence"),
col = rev(heat.colors(100)), names = FALSE,
...)
{
kind <- match.arg(kind)
if (kind == "temperature")
z <- x$u
else z <- x$comm
z <- t(z[nrow(z):1, ])
image(z, axes = FALSE, col = col, ...)
box()
lines(x$smooth$x, 1 - x$smooth$y)
if (length(names) == 1)
names <- rep(names, 2)
if (names[1]) {
axis(2, at = seq(1, 0, len = nrow(x$u)), labels = rownames(x$u),
las = 2, ...)
}
if (names[2]) {
axis(3, at = seq(0, 1, len = ncol(x$u)), labels = colnames(x$u),
las = 2, ...)
}
}
`plot.nestednodf` <-
function(x, col = "red", names = FALSE, ...)
{
z <- x$comm
z <- t(z[nrow(z):1,])
if (length(col) == 1)
col <- c(NA, col)
image(z, axes = FALSE, col = col, ...)
box()
if (length(names) == 1)
names <- rep(names, 2)
if (names[1]) {
axis(2, at = seq(1, 0, len = ncol(z)), labels = rev(colnames(z)),
las = 2, ...)
}
if (names[2]) {
axis(3, at = seq(0, 1, len = nrow(z)), labels = rownames(z),
las = 2, ...)
}
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.nestedtemp.R
|
plot.ordipointlabel <- function (x, ...)
{
plot(x$points, pch = x$args$pch, cex = x$args$pcex, col = x$args$pcol,
bg = x$args$pbg, asp = 1, ...)
font <- attr(x$labels, "font")
if (is.null(font))
font <- par("font")
text(x$labels, rownames(x$labels), cex = x$args$tcex, col = x$args$tcol,
font = font, ...)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.ordipointlabel.R
|
`plot.ordisurf` <- function(x, what = c("contour","persp","gam"),
add = FALSE, bubble = FALSE, col = "red", cex = 1,
nlevels = 10, levels, labcex = 0.6,
lwd.cl = par("lwd"), ...) {
what <- match.arg(what)
y <- x$model$y
x1 <- x$model$x1
x2 <- x$model$x2
X <- x$grid$x
Y <- x$grid$y
Z <- x$grid$z
force(col)
force(cex)
if(isTRUE(all.equal(what, "contour"))) {
if(!add) {
if(bubble) {
if (is.numeric(bubble))
cex <- bubble
cex <- (y - min(y))/diff(range(y)) * (cex-0.4) + 0.4
}
plot(x1, x2, asp = 1, cex = cex, ...)
}
if (missing(levels))
levels <- pretty(range(x$grid$z, finite = TRUE), nlevels)
contour(X, Y, Z, col = col, add = TRUE,
levels = levels, labcex = labcex,
drawlabels = !is.null(labcex) && labcex > 0,
lwd = lwd.cl)
} else if(isTRUE(all.equal(what, "persp"))) {
persp(X, Y, Z, col = col, cex = cex, ...)
} else {
class(x) <- class(x)[-1]
plot(x, ...) ##col = col, cex = cex, ...)
class(x) <- c("ordisurf", class(x))
}
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.ordisurf.R
|
`plot.orditkplot` <-
function(x, ...)
{
op <- par(x$par)
on.exit(par(op))
plot(x$points, pch = x$args$pch, cex = x$args$pcex, col = x$args$pcol,
bg = x$args$pbg, xlim = x$args$xlim, ylim = x$args$ylim, asp=1)
font <- attr(x$labels, "font")
if (is.null(font))
font <- par("font")
text(x$labels, rownames(x$labels), cex = x$args$tcex,
col = x$args$tcol, font = font)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.orditkplot.R
|
## S3 plot method for permat
`plot.permat` <-
function(x, type = "bray", ylab, xlab, col, lty, lowess=TRUE, plot=TRUE, text=TRUE, ...)
{
type <- match.arg(type, c("bray", "chisq"))
if (missing(xlab))
xlab <- "Runs"
if (missing(col))
col <- c(2,4)
if (missing(lty))
lty <- c(1,2)
n <- attr(x, "times")
toplot <- numeric(n)
if (type == "bray") {
toplot <- summary(x)$bray
if (missing(ylab))
ylab <- "Bray-Curtis dissimilarity"
}
if (type == "chisq") {
toplot <- summary(x)$chisq
if (missing(ylab))
ylab <- "Chi-squared"
}
if (plot) {
plot(toplot,type="n",ylab=ylab,xlab=xlab, ...)
lines(toplot,col=col[1], lty=lty[1])
if (lowess)
lines(lowess(toplot),col=col[2], lty=lty[2])
if (text) title(sub=paste("(mean = ", substitute(z, list(z=round(mean(toplot),3))),
", min = ", substitute(z, list(z=round(min(toplot),3))),
", max = ", substitute(z, list(z=round(max(toplot),3))), ")", sep=""))
}
invisible(toplot)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.permat.R
|
`plot.poolaccum` <-
function(x, alpha = 0.05, type = c("l","g"), ...)
{
m <- summary(x, alpha = alpha, ...)
n <- nrow(m[[1]])
Size <- as.vector(sapply(m, function(x) c(x[,1], x[,1], rev(x[,1]))))
Richness <- as.vector(sapply(m, function(x) c(x[,2], x[,3], rev(x[,4]))) )
indnames <- as.character(sapply(m, function(x) colnames(x[,2, drop=FALSE])))
Index <- factor(rep(indnames, each = 3 * n), levels = indnames)
lintype <- rep(c(rep("aver", n), rep("envel", 2*n)), length=length(Size))
xyplot(Richness ~ Size | Index, as.table = TRUE, groups = lintype,
type = type, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.poolaccum.R
|
`plot.prc` <-
function (x, species = TRUE, select, scaling = "symmetric", axis = 1,
correlation = FALSE, const, type = "l", xlab, ylab, ylim,
lty = 1:5, col = 1:6, pch, legpos, cex = 0.8, ...)
{
## save level names before getting the summary
levs <- x$terminfo$xlev[[2]]
x <- summary(x, axis = axis, scaling = scaling, const,
correlation = correlation)
oldpar <- par(no.readonly = TRUE)
on.exit(par(oldpar))
b <- t(coef(x))
xax <- rownames(b)
if (missing(xlab))
xlab <- x$names[1]
if (missing(ylab))
ylab <- "Effect"
if (!missing(select))
x$sp <- .checkSelect(select, x$sp)
if (missing(ylim))
ylim <- if (species)
range(b, x$sp, na.rm = TRUE)
else range(b, na.rm = TRUE)
if (species) {
op <- par("mai")
mrg <- max(strwidth(names(x$sp), cex = cex, units = "in")) +
strwidth("mmm", cex = cex, units = "in")
par(mai = c(op[1:3], max(op[4], mrg)))
}
if (missing(pch))
pch <- as.character(1:nrow(b))
matplot(xax, b, type = type, xlab = xlab, ylab = ylab, ylim = ylim,
cex = cex, lty = lty, col = col, pch = pch, ...)
abline(h = 0, col = "gray")
if (species) {
linestack(x$sp, at = par("usr")[2], add = TRUE, hoff = 1,
cex = cex, ...)
rug(x$sp, side = 4)
}
if (missing(legpos)) {
holes <- abs(par("usr")[3:4] - range(b, na.rm = TRUE))
if (holes[1] > holes[2])
legpos <- "bottomleft"
else legpos <- "topleft"
}
if (!is.na(legpos)) {
nl <- length(levs)
pp <- type %in% c("b", "p")
pl <- type %in% c("b", "l")
if (length(lty) == 1)
lty <- rep(lty, nl-1)
legend(legpos, legend = levs, col = c("gray", col),
lty = if (pl) lty[c(1,1:(nl-1))],
pch = if (pp) pch, cex = cex, title = x$names[2])
}
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.prc.R
|
### Similar plotting functions as plot.prestonfit/fisherfit, but only
### for the data without the fitted models. These can be used with the
### result of as.preston(), as.fisher().
## as plot.prestonfit, but plots only the bars of as.preston()
`plot.preston` <-
function (x, xlab = "Frequency", ylab = "Species", bar.col = "skyblue",
...)
{
freq <- x
oct <- as.numeric(names(freq))
noct <- max(oct) + 1
plot(oct, freq, type = "n", ylim = c(0, max(freq)),
xlim = c(-1, max(oct)), ylab = ylab, xlab = xlab, axes = FALSE, ...)
axis(2)
axis(1, at = 0:noct, labels = 2^(0:noct))
box()
rect(oct - 1, 0, oct, freq, col = bar.col, ...)
invisible()
}
`lines.preston` <-
function(x, xadjust = 0.5, ...)
{
oct <- as.numeric(names(x)) - xadjust
lines(oct, x, ...)
}
## as plot.fisherfit, but plots only the bars of as.fisherfit
`plot.fisher` <-
function(x, xlab = "Frequency", ylab = "Species", bar.col = "skyblue",
kind = c("bar", "hiplot", "points", "lines"), add = FALSE,
...)
{
kind <- match.arg(kind)
freq <- as.numeric(names(x))
if (!add)
plot(freq, x, ylab=ylab, xlab=xlab,
ylim=c(0,max(x)), xlim=c(0.5, max(freq)+0.5), type="n", ...)
switch(kind,
"bar" = rect(freq-0.5,0,freq+0.5,x, col=bar.col, ...),
"hiplot" = points(freq, x, col =bar.col, type = "h", ...),
"points" = points(freq, x, col =bar.col, ...),
"lines" = lines(freq, x, col =bar.col, ...)
)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.preston.R
|
"plot.prestonfit" <-
function (x, xlab = "Frequency", ylab = "Species", bar.col = "skyblue",
line.col = "red", lwd = 2, ...)
{
freq <- x$freq
oct <- as.numeric(names(freq))
noct <- max(oct) + 1
plot(oct, freq, type = "n", ylim = c(0, max(freq)), xlim = c(-1,
max(oct)), ylab = ylab, xlab = xlab, axes = FALSE, ...)
axis(2)
axis(1, at = 0:noct, labels = 2^(0:noct))
box()
rect(oct - 1, 0, oct, freq, col = bar.col, ...)
p <- x$coefficients
curve(p[3] * exp(-(x - p[1])^2/2/p[2]^2), -1, max(oct), add = TRUE,
col = line.col, lwd = lwd, ...)
segments(p["mode"], 0, p["mode"], p["S0"], col = line.col, ...)
segments(p["mode"] - p["width"], p["S0"] * exp(-0.5), p["mode"] +
p["width"], p["S0"] * exp(-0.5), col = line.col, ...)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.prestonfit.R
|
"plot.procrustes" <-
function (x, kind = 1, choices = c(1,2), to.target = TRUE,
type = "p", xlab, ylab, main, ar.col = "blue",
length = 0.05, cex = 0.7, ...)
{
type <- match.arg(type, c("points", "text", "none"))
if (to.target) {
tails <- x$Yrot[, choices]
heads <- x$X[, choices]
} else {
tails <- x$X[, choices]
heads <- x$Yrot[, choices]
}
if (missing(main))
main <- "Procrustes errors"
if (kind <= 1) {
if (missing(xlab))
xlab <- paste("Dimension", choices[1])
if (missing(ylab))
ylab <- paste("Dimension", choices[2])
xrange <- range(tails[, 1], heads[, 1])
yrange <- range(tails[, 2], heads[, 2])
plot(xrange, yrange, xlab = xlab, ylab = ylab, main = main,
type = "n", asp = 1, ...)
if (kind > 0) {
abline(v = 0, lty = 2)
abline(h = 0, lty = 2)
if (ncol(x$rotation) == 2) {
## Draw rotated axes only if they visibly differ from
## unrotated axes
b <- abs(x$rotation[1,1])
EPS <- 1e-8
if (1 - b > EPS && b > EPS) {
rot <- x$rotation
abline(0, rot[1,2]/rot[1,1], lty = 1)
abline(0, rot[2,2]/rot[2,1], lty = 1)
} else {
abline(v = 0, h = 0)
}
}
else {
Y <- x$Yrot %*% t(x$rotation)
for (k in 1:ncol(Y)) {
tmp <- matrix(0, nrow=2, ncol = ncol(Y))
tmp[,k] <- range(Y[,k])
tmp <- tmp %*% x$rotation
lines(tmp[,choices], lty=1)
text(tmp[2,choices[1]], tmp[2,choices[2]], as.character(k))
}
}
if (type != "none") {
ow <- options(warn = -1)
arrows(tails[, 1], tails[, 2], heads[, 1], heads[, 2],
col = ar.col, length = length, ...)
options(ow)
if (type == "text" && !is.null(rownames(tails)))
ordilabel(tails, cex = cex, ...)
else
points(tails, cex = cex, ...)
}
}
out <- list(heads = heads, points = tails)
class(out) <- "ordiplot"
}
else if (kind == 2) {
if (missing(xlab))
xlab <- "Index"
if (missing(ylab))
ylab <- "Procrustes residual"
res <- residuals(x)
q <- quantile(res)
plot(res, type = "h", xlab = xlab, ylab = ylab, main = main,
...)
abline(h = q[2:4], lty = c(2, 1, 2))
out <- list(sites = cbind(seq(along = res), res))
class(out) <- "ordiplot"
}
invisible(out)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.procrustes.R
|
"plot.rad" <-
function(x, xlab="Rank", ylab="Abundance", log = "y", ...)
{
rnk <- seq(along=x)
plot(rnk, x, log=log, xlab=xlab, ylab=ylab, ...)
out <- list(species = cbind(rnk, x))
class(out) <- "ordiplot"
invisible(out)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.rad.R
|
`plot.radfit` <-
function (x, BIC = FALSE, legend = TRUE, ...)
{
if (length(x$y) == 0)
stop("no species, nothing to plot")
## if 'type = "n"', do not add legend (other types are not
## supported)
type <- match.call(expand.dots = FALSE)$...$type
if (is.null(type))
type <- ""
out <- plot(x$y, ...)
if (length(x$y) == 1)
return(invisible(out))
fv <- fitted(x)
if (BIC)
k = log(length(x$y))
else k = 2
emph <- which.min(sapply(x$models, AIC, k = k))
lwd <- rep(1, ncol(fv))
lwd[emph] <- 3
matlines(fv, lty = 1, lwd = lwd, ...)
if (legend && type != "n") {
nm <- names(x$models)
legend("topright", legend = nm, lty = 1, lwd = lwd, col = 1:6)
}
invisible(out)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.radfit.R
|
"plot.radfit.frame" <-
function (x, order.by, BIC = FALSE, model, legend = TRUE, as.table = TRUE,
...)
{
modnam <- names(x[[1]]$models)
if (!missing(model))
pick <- pmatch(model, modnam, nomatch = FALSE)
else pick <- FALSE
pickmod <- function(x, pick, BIC) {
if (pick)
return(pick)
else {
k <- if (BIC)
log(length(x$y))
else 2
which.min(AIC(x, k))
}
}
Nhm <- length(x)
Abundance <- unlist(lapply(x, function(x) x$y))
Rank <- unlist(lapply(x, function(x) if (length(x$y) > 0) seq_along(x$y) else NULL))
Site <- unlist(lapply(x, function(x) length(x$y)))
N <- Site
sitenames <- names(Site)
Site <- rep(names(Site), Site)
if (missing(order.by))
order.by <- 1:Nhm
else order.by <- order(order.by)
Site <- factor(Site, levels = sitenames[order.by])
fit <- unlist(lapply(x, function(x)
as.matrix(fitted(x))[, pickmod(x,
pick, BIC)]))
take <- sapply(x, function(x) pickmod(x, pick, BIC))
take <- rep(take, N)
cols <- trellis.par.get("superpose.line")$col
cols <- cols[seq_along(cols)]
if (legend) {
mykey <- list(text = list(text = modnam), lines = list(lty = 1,
col = cols[seq_along(modnam)], lwd = 2), columns = 3)
}
else {
mykey <- NULL
}
tics <- function(x = max(Abundance), z = min(Abundance)) {
ii <- round(c(log10(z), log10(x)))
x10 <- 10^(ii[1]:ii[2])
if (length(x10) < 3)
x10 <- c(outer(c(1, 2, 5), x10))
else if (length(x10) < 6)
x10 <- c(outer(c(1, 3), x10))
x10[x10 <= x & x10 >= z]
}
out <- xyplot(Abundance ~ Rank | Site, subscripts = TRUE,
as.table = as.table, key = mykey, scales = list(y = list(log = 10,
at = tics())), panel = function(x, y, subscripts) {
panel.xyplot(x, y, ...)
panel.xyplot(x, log10(fit[subscripts]), type = "l",
col = cols[take[min(subscripts)]], lwd = 2, ...)
}, ...)
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.radfit.frame.R
|
"plot.radline" <-
function (x, xlab = "Rank", ylab = "Abundance", type = "b", ...)
{
rad <- x$y
fit <- fitted(x)
rnk <- seq(along = rad)
plot(rnk, rad, log = "y", xlab = xlab, ylab = ylab, type = "n",
...)
out <- NULL
if (type == "b" || type == "p")
out <- points(x, ...)
if (type == "b" || type == "l")
lines(x, ...)
invisible(out)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.radline.R
|
`plot.renyi` <-
function(x, ...)
{
if (inherits(x, "data.frame")) {
plt <- factor(rep(rownames(x), ncol(x)), levels=rownames(x))
alp <- factor(rep(colnames(x), each=nrow(x)), levels=colnames(x))
div <- as.vector(as.matrix(x))
df <- data.frame(diversity=div, plot=plt, alpha=alp)
lo <- tapply(div, alp, min)
hi <- tapply(div, alp, max)
med <- tapply(div, alp, median)
} else {
df <- data.frame(diversity = x, alpha = factor(names(x), levels=names(x)), plot = "plot")
lo <- hi <- med <- NA
}
cl <- trellis.par.get("superpose.line")$col
bwplot(diversity ~ alpha | plot, data=df,
panel = function(x, y, ...) {
panel.lines(x, lo, lty=2, col=cl[3])
panel.lines(x, med, lty=2, col=cl[2])
panel.lines(x, hi, lty=2, col=cl[3])
panel.xyplot(x, y, ...)
},
...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.renyi.R
|
`plot.renyiaccum` <-
function (x, what=c("Collector", "mean", "Qnt 0.025", "Qnt 0.975"),
type = "l", ...)
{
what <- what[what %in% dimnames(x)[[3]]]
if (any(what %in% dimnames(x)[[3]]))
x <- x[,,what, drop = FALSE]
dm <- dim(x)
dnam <- dimnames(x)
lin <- rep(dnam[[3]], each=dm[1]*dm[2])
Sites <- rep(1:dm[1], len=prod(dm))
alp <- factor(dnam[[2]], levels=dnam[[2]])
alpha <- rep(rep(alp, each=dm[1]), len=prod(dm))
Diversity <- as.vector(x)
xyplot(Diversity ~ Sites | alpha, groups=lin, type=type, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.renyiaccum.R
|
`plot.spantree` <-
function (x, ord, cex = 0.7, type = "p", labels, dlim, FUN = sammon,
...)
{
FUNname <- deparse(substitute(FUN))
FUN <- match.fun(FUN)
n <- x$n
if (missing(ord)) {
d <- cophenetic(x)
if (any(d<=0))
d[d<=0] <- min(d>0)/10
if (!missing(dlim))
d[d > dlim ] <- dlim
if (n > 2) {
## sammon needs extra care, for other cases we just try FUN(d)
if (FUNname == "sammon") {
y <- cmdscale(d)
dup <- duplicated(y)
if (any(dup))
y[dup, ] <- y[dup,] + runif(2*sum(dup), -0.01, 0.01)
ord <- FUN(d, y = y)
} else
ord <- FUN(d)
} else
ord <- cbind(seq_len(n), rep(0,n))
}
ord <- scores(ord, display = "sites", ...)
ordiArgAbsorber(ord, asp = 1, type = "n", FUN = "plot", ...)
lines(x, ord, ...)
if (type == "p" || type == "b")
ordiArgAbsorber(ord, cex = cex, FUN = "points", ...)
else if (type == "t") {
if (missing(labels))
labels <- x$labels
x <- scores(ord, display = "sites", ...)
ordiArgAbsorber(x, labels = labels, cex = cex, FUN = "ordilabel", ...)
}
ord <- list(sites = ord)
class(ord) <- "ordiplot"
invisible(ord)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.spantree.R
|
`plot.specaccum` <-
function(x, add = FALSE, random = FALSE, ci = 2,
ci.type = c("bar","line","polygon"), col = par("fg"), lty = 1,
ci.col = col, ci.lty = 1, ci.length = 0, xlab, ylab = x$method,
ylim, xvar = c("sites", "individuals", "effort"), ...)
{
if(random && !(x$method %in% c("random", "collector")))
stop("random = TRUE can be used only with method='random'")
if(x$method == "collector")
random <- TRUE
xvar <- match.arg(xvar)
## adjust weights to number of sites
if (random && !is.null(x$weights) && xvar == "sites") {
n <- length(x$effort)
adj <- n/x$effort[n]
} else {
adj <- 1
}
xaxvar <- x[[xvar]]
if (missing(xlab))
xlab <- paste(toupper(substring(xvar, 1, 1)),
substring(xvar, 2), sep="")
if (random)
ci <- FALSE
ci.type <- match.arg(ci.type)
if (!add) {
if (missing(ylim))
if (random)
ylim <- c(min(1, x$perm), max(x$perm, na.rm = TRUE))
else
ylim <- c(min(1, x$richness),
max(x$richness, x$richness + ci*x$sd, na.rm = TRUE))
plot(xaxvar, x$richness, xlab=xlab, ylab=ylab, ylim=ylim,
type="n", ...)
}
if (!is.null(x$sd) && ci)
switch(ci.type,
bar = {k <- x$sd > sqrt(.Machine$double.eps)
arrows(xaxvar[k], (x$richness - ci*x$sd)[k], xaxvar[k],
(x$richness + ci*x$sd)[k], col=ci.col, lty=ci.lty,
length = ci.length, angle = 90, code = 3, ...)},
line = matlines(xaxvar, x$richness + t(rbind(-ci,ci) %*% x$sd),
col=ci.col, lty=ci.lty, ...),
polygon = polygon(c(xaxvar, rev(xaxvar)),
c(x$richness - ci*x$sd, rev(x$richness + ci*x$sd)), col=ci.col,
lty=ci.lty, ...)
)
if (random) {
if (is.null(x$weights)) {
for(i in seq_len(NCOL(x$perm)))
lines(xaxvar, x$perm[,i], col=col, ...)
} else {
for(i in seq_len(NCOL(x$perm)))
lines(x$weights[,i]*adj, x$perm[,i], col=col, ...)
}
} else
lines(xaxvar, x$richness, col=col, lty = lty, ...)
invisible()
}
`lines.specaccum` <-
function(x, ...)
{
plot(x, add = TRUE, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.specaccum.R
|
`plot.taxondive` <-
function (x, ...)
{
plot(x$Species, x$Dplus, xlab="Number of Species", ylab=expression(Delta^"+"), ...)
i <- order(x$Species)
abline(h=x$EDplus, ...)
lines(x$Species[i], x$EDplus - 2*x$sd.Dplus[i], ...)
lines(x$Species[i], x$EDplus + 2*x$sd.Dplus[i], ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.taxondive.R
|
"plot.varpart" <-
function(x, ...)
{
plot(x$part, ...)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.varpart.R
|
"plot.varpart234" <-
function(x, cutoff = 0, digits = 1, ...)
{
vals <- x$indfract[, 3]
is.na(vals) <- vals < cutoff
if (cutoff >= 0)
vals <- round(vals, digits+1)
labs <- format(vals, digits=digits, nsmall=digits+1)
labs <- gsub("NA", "", labs)
showvarparts(x$nsets, labs, ...)
if (any(is.na(vals)))
mtext(paste("Values <", cutoff," not shown", sep=""), 1)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/plot.varpart234.R
|
`points.cca` <-
function (x, display = "sites", choices = c(1, 2), scaling = "species",
arrow.mul, head.arrow = 0.05, select, const, axis.bp = FALSE,
correlation = FALSE, hill = FALSE, ...)
{
if (length(display) > 1)
stop("only one 'display' item can be added in one command")
pts <- scores(x, choices = choices, display = display, scaling = scaling,
const, correlation = correlation, hill = hill, tidy=FALSE)
if (!missing(select))
pts <- .checkSelect(select, pts)
if (display == "cn") {
cnam <- rownames(pts)
points(pts, ...)
pts <- scores(x, choices = choices, display = "bp", scaling = scaling,
const, correlation = correlation, hill = hill)
bnam <- rownames(pts)
pts <- pts[!(bnam %in% cnam), , drop = FALSE]
if (nrow(pts) == 0)
return(invisible())
else display <- "bp"
}
if (display %in% c("bp", "reg", "re", "r")) {
if (missing(arrow.mul)) {
arrow.mul <- ordiArrowMul(pts)
}
pts <- pts * arrow.mul
arrows(0, 0, pts[, 1], pts[, 2], length = head.arrow,
...)
pts <- pts * 1.1
if (axis.bp) {
axis(3, at = c(-arrow.mul, 0, arrow.mul),
labels = rep("", 3))
axis(4, at = c(-arrow.mul, 0, arrow.mul),
labels = c(-1, 0, 1))
}
return(invisible())
}
points(pts, ...)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/points.cca.R
|
"points.decorana" <-
function (x, display=c("sites", "species"), choices=1:2, origin = TRUE,
select, ...)
{
display <- match.arg(display)
x <- scores(x, display = display, choices = choices, origin = origin, ...)
if (!missing(select))
x <- .checkSelect(select, x)
ordiArgAbsorber(x, FUN = points, ...)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/points.decorana.R
|
"points.metaMDS" <-
function (x, display = c("sites", "species"),
choices = c(1, 2), shrink = FALSE, select, ...)
{
display <- match.arg(display)
x <- scores(x, display = display, choices = choices, shrink = shrink)
if (!missing(select))
x <- .checkSelect(select, x)
points(x, ...)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/points.metaMDS.R
|
`points.ordiplot` <-
function (x, what, select, arrows = FALSE, ...)
{
sco <- scores(x, what)
if (!missing(select))
sco <- .checkSelect(select, sco)
## draw adjusted arrows automatically for biplot scores
scoatt <- attr(sco, "score")
if (!is.null(scoatt) && scoatt %in% c("biplot", "regression")) {
arrows = TRUE
sco <- sco * ordiArrowMul(sco)
}
## draw arrows when requested, also for "species" etc
if (arrows) {
arrows(0, 0, sco[,1], sco[,2], ...)
} else {
points(sco, ...)
}
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/points.ordiplot.R
|
`points.orditkplot` <- function(x, pch = x$args$pch, cex = x$args$pcex,
col = x$args$pcol, bg = x$args$pbg, ...) {
points(x$points, pch = pch, cex = cex, col = col, bg = bg, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/points.orditkplot.R
|
`points.procrustes` <-
function(x, display = c("target","rotated"), choices = c(1,2),
truemean = FALSE, ...)
{
display <- match.arg(display)
X <- if (display == "target") x$X else x$Yrot
X <- X[, choices, drop = FALSE]
if (truemean)
X <- sweep(X, 2, x$xmean[choices], "+")
ordiArgAbsorber(X, FUN = points, ...)
invisible()
}
`text.procrustes` <-
function(x, display = c("target","rotated"), choices = c(1,2),
labels, truemean = FALSE, ...)
{
display <- match.arg(display)
X <- if (display == "target") x$X else x$Yrot
X <- X[, choices, drop = FALSE]
if (truemean)
X <- sweep(X, 2, x$xmean[choices], "+")
if (missing(labels))
labels <- rownames(X)
ordiArgAbsorber(X, labels = labels, FUN = text, ...)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/points.procrustes.R
|
`points.radline` <-
function (x, ...)
{
poi <- x$y
rnk <- seq(along = poi)
points(rnk, poi, ...)
out <- list(species = cbind(rnk, poi))
class(out) <- "ordiplot"
invisible(out)
}
`points.radfit` <-
function(x, ...)
{
points.radline(x, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/points.radline.R
|
`poolaccum` <-
function(x, permutations = 100, minsize = 3)
{
x <- as.matrix(x)
n <- nrow(x)
m <- ncol(x)
N <- seq_len(n)
## specpool() is slow, but the vectorized versions below are
## pretty fast. We do not set up parallel processing, but use
## permute API.
permat <- getPermuteMatrix(permutations, n)
nperm <- nrow(permat)
S <- chao <- boot <- jack1 <- jack2 <-
matrix(0, nrow=n, ncol=nperm)
for (i in 1:nperm) {
## It is a bad practice to replicate specpool equations here:
## if we change specpool, this function gets out of sync. You
## should be ashamed, Jari Oksanen!
take <- permat[i,]
tmp <- apply(x[take,] > 0, 2, cumsum)
S[,i] <- rowSums(tmp > 0)
## All-zero species are taken as *known* to be missing in
## subsamples, and in the following we subtract them (as
## 2*S-m) from the bootstrap samples to give a more unbiased
## estimate.
boot[,i] <- 2*S[,i] - m + rowSums(exp(sweep(log1p(-sweep(tmp, 1, N, "/")), 1, N, "*") ))
a1 <- rowSums(tmp == 1)
a2 <- rowSums(tmp == 2)
chao[, i] <- S[,i] + ifelse(a2 > 0, (N-1)/N*a1*a1/2/a2,
(N-1)/N*a1*(a1-1)/2)
jack1[,i] <- S[,i] + a1 * (N-1)/N
jack2[,i] <- S[,i] + a1*(2*N-3)/N - a2*(N-2)^2/N/(N-1)
}
means <- cbind(`N` = N, `S` = rowMeans(S), `Chao` = rowMeans(chao),
`Jackknife 1` = rowMeans(jack1),
`Jackknife 2` = rowMeans(jack2),
`Bootstrap` = rowMeans(boot))
take <- N >= minsize
out <- list(S = S[take,], chao = chao[take,], jack1 = jack1[take,],
jack2 = jack2[take,], boot = boot[take,], N = N[take],
means = means[take,])
attr(out, "control") <- attr(permat, "control")
class(out) <- "poolaccum"
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/poolaccum.R
|
`postMDS` <-
function (X, dist, pc = TRUE, center = TRUE, halfchange,
threshold = 0.8, nthreshold = 10, plot = FALSE, ...)
{
Size <- attr(dist, "Size")
if (any(names(X) == "points"))
x <- X$points
else x <- as.matrix(X)
if (center)
x <- scale(x, scale = FALSE)
if (pc) {
dn <- dimnames(x)
x <- prcomp(x, center = center)$x
dimnames(x) <- dn
}
## Check halfchange scaling, if not explicitly defined
maxdist <- attr(dist, "maxdist")
if (missing(halfchange)) {
## play safe: if 'maxdist' is missing or NA, skip halfchange
## scaling. vegdist sets attr maxdist, and for other distfuns,
## metaMDSdist tries to find maxdist. Dissimilarity input may
## not have this attribute and are not halfchange scaled.
if (!is.null(maxdist) && !is.na(maxdist) && is.numeric(maxdist))
halfchange <- TRUE
else
halfchange <- FALSE
}
if (halfchange) {
dist <- as.vector(dist)
ordi <- as.vector(vegdist(x, "euclidean"))
## adjust threshold to maxdist if available
if (!is.numeric(maxdist))
warning("halfchange requested, but ceiling distance is unknown, using ", threshold)
else {
threshold <- maxdist * threshold
## something fishy - similarities instead of distances?
if (threshold < sqrt(.Machine$double.eps))
warning("dubious maxdist ", maxdist, ": similarities instead of dissimilarities?")
}
take <- dist < threshold
if (sum(take) < nthreshold) {
warning("skipping half-change scaling: too few points below threshold")
halfchange <- FALSE
}
else {
k <- coef(lm(dist[take] ~ ordi[take]))
names(k) <- NULL
hc <- (1 - k[1])/2/k[2]
x <- x/hc
}
}
if (!halfchange) {
hc <- max(dist(x, "euclidean"))/max(dist, na.rm = TRUE)
x <- x/hc
}
if (plot && halfchange) {
cross.lim <- 45
if (Size > cross.lim)
pch <- "."
else pch <- "+"
orange <- range(c(ordi, 0, 1))
drange <- range(c(dist, 0, 1))
plot(orange, drange, type = "n", xlab = "Ordination distance",
ylab = "Community dissimilarity")
## Colours in default palette: 2 = red, 4 = blue, 8 = gray.
points(ordi[take], dist[take], pch = pch, col = 4)
points(ordi[!take], dist[!take], pch = pch, col = 8)
abline(h = threshold)
abline(h = k[1])
hclevel <- (1 - k[1])/2 + k[1]
segments(0, hclevel, hc, hclevel, col = 2, lwd = 2)
arrows(hc, hclevel, hc, 0, col = 2, lwd = 2)
arrows(0, k[1], 0, hclevel, col = 2, code = 3)
arrows(0, hclevel, 0, 1, col = 2, code = 3)
j <- 0.02
text(0 + j, threshold + j, "Threshold", adj = c(0, 0))
text(0 + j, k[1] + j, "Replicate dissimilarity", adj = c(0,
0))
text(0 + j, hclevel + j, "Half-change", adj = c(0, 0))
abline(k, col = 4, lwd = 2)
}
attr(x, "centre") <- center
attr(x, "pc") <- pc
attr(x, "halfchange") <- halfchange
attr(x, "internalscaling") <- hc
if (any(names(X) == "points"))
X$points <- x
else X <- x
X
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/postMDS.R
|
`prc` <-
function (response, treatment, time, ...)
{
extras <- match.call(expand.dots = FALSE)$...
if (is.null(extras$data))
data <- parent.frame()
else
data <- eval(extras$data)
y <- deparse(substitute(response))
x <- deparse(substitute(treatment))
z <- deparse(substitute(time))
oldcon <- options(contrasts = c("contr.treatment", "contr.poly"))
on.exit(options(oldcon))
fla <- as.formula(paste("~", x, "+", z))
mf <- model.frame(fla, data, na.action = na.pass)
if (!all(sapply(mf, is.factor)))
stop(gettextf("%s and %s must be factors", x, z))
if (any(sapply(mf, is.ordered)))
stop(gettextf("%s or %s cannot be ordered factors", x, z))
fla.zx <- as.formula(paste("~", z, ":", x))
fla.z <- as.formula(paste("~", z))
# delete first (control) level from the design matrix
X = model.matrix(fla.zx, mf)[,-c(seq_len(nlevels(time)+1))]
Z = model.matrix(fla.z, mf)[,-1]
mod <- rda(response ~ X + Condition(Z), ...)
mod$terminfo$xlev = list(levels(time), levels(treatment))
names(mod$terminfo$xlev) = c(paste(z), paste(x))
mod$call <- match.call()
class(mod) <- c("prc", class(mod))
mod
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/prc.R
|
`predict.cca` <-
function (object, newdata, type = c("response", "wa", "sp", "lc", "working"),
rank = "full", model = c("CCA", "CA"), scaling = "none",
hill = FALSE, ...)
{
type <- match.arg(type)
model <- match.arg(model)
if (model == "CCA" && is.null(object$CCA))
model <- "CA"
take <- object[[model]]$rank
if (take == 0)
stop(gettextf("model '%s' has rank 0", model))
if (rank != "full")
take <- min(take, rank)
rs <- object$rowsum
cs <- object$colsum
gtot <- object$grand.tot
u <- object[[model]]$u[, 1:take, drop = FALSE]
v <- object[[model]]$v[, 1:take, drop = FALSE]
w <- object[[model]]$wa[, 1:take, drop = FALSE]
if (is.null(w))
w <- u
slam <- diag(sqrt(object[[model]]$eig[1:take]), nrow = take)
## process scaling arg, scaling used later so needs to be a numeric
scaling <- scalingType(scaling = scaling, hill = hill)
if (type %in% c("response", "working")) {
Xbar <- 0
if (!missing(newdata)) {
if (NROW(u) == NROW(newdata))
u <- predict(object, type = if(model == "CCA") "lc" else "wa",
newdata = newdata, rank = take)
else
warning(gettextf("'newdata' ignored: it must have the same number of rows as the original community data with type = '%s'", type))
}
if (take > 0)
Xbar <- u %*% slam %*% t(v)
rc <- outer(rs, cs)
if (type == "response")
out <- (Xbar + 1) * rc * gtot
else # type == "working"
out <- Xbar * sqrt(rc)
}
else if (type == "lc") {
if (model == "CA")
stop("'lc' scores not available for unconstrained ordination")
if (!missing(newdata)) {
if (is.null(object$terminfo))
E <- as.matrix(newdata)
else {
d <- ordiParseFormula(formula(object), newdata, object$terminfo$xlev)
E <- cbind(d$Z, d$Y)
}
E <- sweep(E, 2, c(object$pCCA$envcentre, object$CCA$envcentre),
"-")
Q <- object[[model]]$QR
p1 <- Q$pivot[1:Q$rank]
u <- E[, p1, drop = FALSE] %*% coef(object)[p1, ,
drop = FALSE]
u <- u[, 1:take, drop = FALSE]
}
out <- u
if (scaling) { # implicit conversion "none" == 0 == FALSE
scal <- list(diag(slam), 1, sqrt(diag(slam)))[[abs(scaling)]]
out <- sweep(out, 2, scal, "*")
if (scaling < 0) {
scal <- sqrt(1/(1 - diag(slam)^2))
out <- sweep(out, 2, scal, "*")
}
}
}
else if (type == "wa") {
if (!missing(newdata)) {
if (!is.null(object$pCCA))
stop("no 'wa' scores available (yet) in partial CCA")
nm <- rownames(v)
if (!is.null(nm)) { # Got rownames: keep only species with scores
if (!all(nm %in% colnames(newdata)))
stop("'newdata' does not have named columns matching one or more the original columns")
newdata <- newdata[, nm, drop = FALSE]
} else { #Rownames are NULL: still try to remove exclude.spec
exclude.spec <- attr(object[[model]]$v, "na.action")
if (!is.null(exclude.spec))
Xbar <- Xbar[, -exclude.spec]
}
Xbar <- as.matrix(newdata)
rs <- rowSums(Xbar)
Xbar <- (Xbar - outer(rs, cs))/sqrt(outer(rs, cs))
v <- sweep(v, 1, sqrt(cs), "*")
w <- sweep(Xbar %*% v, 1, sqrt(rs), "/")
w <- sweep(w, 2, diag(slam), "/")
}
out <- w
if (scaling) { # implicit conversion "none" == 0 == FALSE
scal <- list(diag(slam), 1, sqrt(diag(slam)))[[abs(scaling)]]
out <- sweep(out, 2, scal, "*")
if (scaling < 0) {
scal <- sqrt(1/(1 - diag(slam)^2))
out <- sweep(out, 2, scal, "*")
}
}
}
else if (type == "sp") {
if (!missing(newdata)) {
nm <- rownames(u)
if (!is.null(nm)) {
if (!all(nm %in% rownames(newdata)))
stop("'newdata' does not have named rows matching one or more of the original rows")
newdata <- newdata[nm, , drop = FALSE]
}
Xbar <- as.matrix(newdata)
cs <- colSums(Xbar)
Xbar <- (Xbar - outer(rs, cs))/sqrt(outer(rs, cs))
if (!is.null(object$pCCA))
Xbar <- qr.resid(object$pCCA$QR, Xbar)
u <- sweep(u, 1, sqrt(rs), "*")
v <- sweep(t(Xbar) %*% u, 1, sqrt(cs), "/")
v <- sweep(v, 2, diag(slam), "/")
}
out <- v
if (scaling) { # implicit conversion "none" == 0 == FALSE
scal <- list(1, diag(slam), sqrt(diag(slam)))[[abs(scaling)]]
out <- sweep(out, 2, scal, "*")
if (scaling < 0) {
scal <- sqrt(1/(1 - diag(slam)^2))
out <- sweep(out, 2, scal, "*")
}
}
}
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/predict.cca.R
|
### prediction mainly fails with detrended (and rescaled) analysis
### beyond axis 1 or with 'newdata'. It could be possible to work out
### approximate prediction, but that would require orthogonalizing the
### scores and using additive eigenvalues (evals.ortho): see
### decorana() for orthogonalization.
`predict.decorana` <-
function (object, newdata, type = c("response", "sites", "species"),
rank = 4, ...)
{
type <- match.arg(type)
u <- object$rproj[, 1:rank, drop = FALSE]
v <- object$cproj[, 1:rank, drop = FALSE]
orig <- object$origin[1:rank]
u <- sweep(u, 2, orig, "-")
v <- sweep(v, 2, orig, "-")
rs <- object$aidot
cs <- object$adotj
tot <- sum(rs)
rs <- rs/tot
cs <- cs/tot
lam <- object$evals[1:rank]
if (type == "response") {
if (!object$ira && rank > 1)
stop("prediction is unavailable in detrended CA beyond first axis")
Xbar <- 0
if (rank > 0) {
if (!object$ira) {
tmp <- sweep(v, 1, sqrt(cs), "*")
tmp <- rbind(tmp, sweep(u, 1, sqrt(rs), "*"))
rot <- svd(tmp)$v
v <- v %*% rot
u <- u %*% rot
fac <- colSums(sweep(v^2, 1, cs, "*"))
lam <- (fac - 1)/fac
}
Xbar <- u %*% diag(1 - lam, nrow = rank) %*% t(v)
}
out <- (Xbar + 1) * outer(rs, cs) * tot
}
else if (type == "sites") {
if (!missing(newdata)) {
Xbar <- as.matrix(newdata)
if (!is.null(object$v))
Xbar <- sweep(Xbar, 2, object$v, "*")
rs <- rowSums(Xbar)
Xbar <- (Xbar - outer(rs, cs))/sqrt(outer(rs, cs))
v <- sweep(v, 1, sqrt(cs), "*")
u <- sweep(Xbar %*% v, 1, sqrt(rs), "/")
}
out <- u
}
else if (type == "species") {
if (!missing(newdata)) {
if (!object$ira && rank > 1)
stop("type = 'species' not available in detrended CA with 'newdata'")
if (object$iresc)
stop("type = 'species' not available in rescaled DCA with 'newdata'")
Xbar <- as.matrix(newdata)
cs <- colSums(Xbar)
Xbar <- (Xbar - outer(rs, cs))/sqrt(outer(rs, cs))
u <- sweep(u, 1, sqrt(rs), "*")
v <- sweep(t(Xbar) %*% u, 1, sqrt(cs), "/")
v <- sweep(v, 2, lam, "/")
}
out <- v
}
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/predict.decorana.R
|
### fitspecaccum returns fitted nls() models in item models. Here we
### provide interfaces for some "nls" class support functions, and
### others can be used in the similar way.
`predict.fitspecaccum` <-
function(object, newdata, ...)
{
mods <- object$models
if (!missing(newdata)) {
newdata <- drop(as.matrix(newdata))
if (length(dim(newdata)) > 1)
stop("function accepts only one variable as 'newdata'")
drop(sapply(mods, predict, newdata = data.frame(x = newdata), ...))
} else {
drop(sapply(mods, predict, ...))
}
}
`AIC.fitspecaccum` <-
function(object, ..., k = 2)
{
sapply(object$models, AIC, k = k, ...)
}
`deviance.fitspecaccum` <-
function(object, ...)
{
sapply(object$models, deviance, ...)
}
`logLik.fitspecaccum` <-
function(object, ...)
{
out <- sapply(object$models, logLik, ...)
## sapply() strips attributes: get'em back
attr(out, "df") <- 1L + length(coef(object$models[[1L]]))
attr(out, "nobs") <- nobs(object$models[[1L]])
class(out) <- "logLik"
out
}
`nobs.fitspecaccum` <-
function(object, ...)
{
sapply(object$models, nobs, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/predict.fitspecaccum.R
|
"predict.humpfit" <-
function(object, newdata = NULL, ...)
{
if (is.null(newdata))
return(fitted(object))
else {
p <- coef(object)
x <- unlist(newdata)
x <- ifelse(x < p[1], x/p[1], p[1]*p[1]/x/x)
fv <- p[3]*log(1 + p[2]*x/p[3])
}
fv
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/predict.humpfit.R
|
### predict method for radline, radfit & radfit.frame
### All functions take 'newdata' argument which need not be integer:
### the functions can interpolate, but not necessarily extrapolate, or
### the extrapolations may be NaN.
`predict.radline` <-
function(object, newdata, total, ...)
{
## newdata can be ranks
if (missing(newdata))
x <- seq_along(object$y)
else
x <- drop(as.matrix(newdata))
## total number of individuals in the community
if (missing(total))
total <- sum(object$y)
## adjustment for chagned total in call
adj <- total/sum(object$y)
nobs <- length(object$y)
p <- coef(object)
switch(object$model,
## linear interpolation, no extrapolation
`Brokenstick` = approx(seq_len(nobs),
object$fitted.values, x, ...)$y * adj,
`Preemption` = exp(log(total) + log(p) + log(1 - p)*(x-1)),
## NaN when rank outside proportional rank 0...1
`Log-Normal` = {
slope <- diff(range(ppoints(nobs)))/(nobs-1)
intcpt <- 0.5 - slope * (nobs + 1) / 2
xnorm <- -qnorm(intcpt + slope * x)
exp(p[1] + p[2]*xnorm)*adj
},
`Zipf` = exp(log(total) + log(p[1]) + p[2]*log(x)),
`Zipf-Mandelbrot` = exp(log(total) + log(p[1]) +
p[2]*log(x + p[3]))
)
}
`predict.radfit`<-
function(object, ...)
{
sapply(object$models, predict, ...)
}
`predict.radfit.frame` <-
function(object, ...)
{
lapply(object, predict, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/predict.radline.R
|
### predict.rda handles rda plus distance-based capscale and
### dbrda. Distance-based methods have some limitations:
###
### - type = "response" returns dissimilarities (and ignores imaginary dims)
### - Euclidean distances type = "working" give type = "response"
### - there are no meaningful species scores
### - WA scores with newdata cannot be calculated in capscale.
### - only type = "response", "working" and "lc" work with dbrda
### - only type = "lc" can be used with newdata with dbrda
`predict.rda` <-
function (object, newdata, type = c("response", "wa", "sp", "lc", "working"),
rank = "full", model = c("CCA", "CA"), scaling = "none",
correlation = FALSE, const, ...)
{
## not vegan rda, but intended for klaR:::predict.rda?
if (!("CA" %in% names(object)))
stop(gettextf("%s is not a vegan rda object",
sQuote(deparse(substitute(object)))))
type <- match.arg(type)
model <- match.arg(model)
if (model == "CCA" && is.null(object$CCA))
model <- "CA"
if (inherits(object, "dbrda"))
take <- object[[model]]$poseig
else
take <- object[[model]]$rank
if (take == 0)
stop(gettextf("model '%s' has rank 0", model))
if (rank != "full")
take <- min(take, rank)
if (!inherits(object, "dbrda")) {
## 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)) {
cent <- attr(object$Ybar, "scaled:center")
scal <- 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
cent <- attr(tmp, "scaled:center")
scal <- attr(tmp, "scaled:scale")
}
scaled.PCA <- !is.null(scal)
}
nr <- nobs(object) - 1
u <- object[[model]]$u[, 1:take, drop = FALSE]
w <- object[[model]]$wa[, 1:take, drop = FALSE]
if (is.null(w))
w <- u
if (!inherits(object, "dbrda")) {
v <- object[[model]]$v[, 1:take, drop = FALSE]
}
## process scaling arg, scaling used later so needs to be a numeric
scaling <- scalingType(scaling = scaling, correlation = correlation)
if (type %in% c("wa","sp","lc")) {
slam <- sqrt(object[[model]]$eig[1:take]/object$tot.chi)
if (scaling && missing(const))
const <- sqrt(sqrt((nobs(object)-1) * object$tot.chi))
} else {
slam <- diag(sqrt(object[[model]]$eig[1:take]), nrow = take)
}
if (type %in% c("response", "working")) {
if (!missing(newdata)) {
u <- predict(object, type = if(model == "CCA") "lc" else "wa",
newdata = newdata, rank = take)
}
if (inherits(object, c("capscale", "dbrda"))) {
if (take > 0) {
out <- u %*% slam
if (type == "response") {
out <- dist(out)
if (!is.null(object$ac)) {
if (object$add == "lingoes")
out <- sqrt(out^2 - 2 * object$ac)
else if (object$add == "cailliez")
out <- out - object$ac
else
stop("unknown euclidifying adjustment")
}
if (object$sqrt.dist)
out <- out^2
}
}
} else {
if (take > 0)
out <- u %*% slam %*% t(v)
else {
out <- matrix(0, nrow = nrow(u), ncol = nrow(v))
rownames(out) <- rownames(u)
colnames(out) <- rownames(v)
}
if (type == "response") {
if (!is.null(scal))
out <- sweep(out, 2, scal, "*")
out <- out * sqrt(nr)
out <- sweep(out, 2, cent, "+")
}
}
}
else if (type == "lc") {
if (model == "CA")
stop("'lc' scores not available for unconstrained ordination")
if (!missing(newdata)) {
if (is.null(object$terminfo))
E <- as.matrix(newdata)
else {
d <- ordiParseFormula(formula(object), newdata,
object$terminfo$xlev)
E <- cbind(d$Z, d$Y)
}
Q <- object[[model]]$QR
p1 <- Q$pivot[1:Q$rank]
E <- sweep(E, 2, c(object$pCCA$envcentre, object$CCA$envcentre),
"-")
u <- E[, p1, drop = FALSE] %*% coef(object)[p1, ,
drop = FALSE]
u <- u[, 1:take, drop = FALSE]
}
out <- u
if (scaling) { # implicit coercion 0 == FALSE, other == TRUE
lam <- list(slam, 1, sqrt(slam))[[abs(scaling)]]
out <- const * sweep(out, 2, lam, "*")
}
}
else if (type == "wa") {
if (!missing(newdata)) {
if (inherits(object, c("capscale", "dbrda")))
stop(gettextf("'wa' scores not available in %s with 'newdata'",
object$method))
if (!is.null(object$pCCA))
stop("no 'wa' scores available (yet) in partial RDA")
nm <- rownames(v)
if (!is.null(nm)) {
if (!all(nm %in% colnames(newdata)))
stop("'newdata' does not have named columns matching one or more the original columns")
newdata <- newdata[, nm, drop = FALSE]
}
Xbar <- as.matrix(newdata)
Xbar <- sweep(Xbar, 2, cent, "-")
Xbar <- Xbar / sqrt(nr)
if (!is.null(scal)) {
nz <- scal > 0
Xbar[,nz] <- sweep(Xbar[,nz], 2, scal[nz], "/")
}
w <- Xbar %*% v
w <- sweep(w, 2, slam, "/") / sqrt(object$tot.chi)
}
out <- w
if (scaling) { # implicit coercion 0 == FALSE, other == TRUE
lam <- list(slam, 1, sqrt(slam))[[abs(scaling)]]
out <- const * sweep(out, 2, lam, "*")
}
}
else if (type == "sp") {
if (inherits(object, "capscale"))
warning("'sp' scores may be meaningless in 'capscale'")
if (inherits(object, "dbrda"))
stop("'sp' scores are not available in 'dbrda'")
if (!missing(newdata)) {
nm <- rownames(u)
if (!is.null(nm)) {
if (!all(nm %in% rownames(newdata)))
stop("'newdata' does not have named rows matching one or more of the original rows")
newdata <- newdata[nm, , drop = FALSE]
}
Xbar <- as.matrix(newdata)
Xbar <- scale(Xbar, center = TRUE, scale = scaled.PCA)
Xbar <- Xbar/sqrt(nr)
if (!is.null(object$pCCA))
Xbar <- qr.resid(object$pCCA$QR, Xbar)
v <- t(Xbar) %*% u
v <- sweep(v, 2, slam, "/") / sqrt(object$tot.chi)
}
out <- v
if (scaling) { # implicit coercion 0 == FALSE, other == TRUE
lam <- list(1, slam, sqrt(slam))[[abs(scaling)]]
out <- const * sweep(out, 2, lam, "*")
if (scaling < 0) { # correlation=TRUE
out <- out / object$colsum
out <- out * sqrt(object$tot.chi / (nobs(object)-1))
}
}
}
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/predict.rda.R
|
`predict.specaccum` <-
function(object, newdata, interpolation = c("linear", "spline"), ...)
{
if (missing(newdata))
out <- object$richness
else {
interpolation <- match.arg(interpolation)
newdata <- drop(as.matrix(newdata))
if (length(dim(newdata)) > 1)
stop("function accepts only one variable as 'newdata'")
## Estimation uses lchoose(), but for predict we need to
## estimates on non-integer sample sizes and therefore we use
## lgamma(). Original "rarefaction" used sample sizes rounded
## to integers, but here we can use non-integer data and hence
## get different results.
if (object$method %in% c("exact", "rarefaction")) {
lg <- function(n, k) {
ifelse(k <= n, lgamma(pmax(n, 0) + 1) - lgamma(k+1) -
lgamma(pmax(n-k, 0) + 1), -Inf)
}
if (object$method == "exact")
n <- length(object$sites)
else {
n <- sum(object$freq)
newdata <- newdata / length(object$sites) * n
}
ldiv <- lg(n, newdata)
out <- numeric(length(ldiv))
for(i in seq_along(newdata)) {
out[i] <- sum(1 - exp(lg(n-object$freq, newdata[i])
- ldiv[i]))
}
} else if (object$method == "coleman") {
## "coleman" also works on non-integer newdata
n <- length(object$sites)
out <- sapply(newdata,
function(x) sum(1 - (1 - x/n)^object$freq))
} else {
## Other methods do not accept non-integer newdata, but we
## can interpolate
if (interpolation == "linear")
out <- approx(x = object$sites, y = object$richness,
xout = newdata, rule = 1)$y
else
out <- spline(x = object$sites, y = object$richness,
xout = newdata, ...)$y
}
}
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/predict.specaccum.R
|
`pregraphKM` <-
function(matrice)
{
`row.col.number` <- function(mat,number){
nr<-nrow(mat)
nc<-ncol(mat)
mod<-number %% nr
div<-number/nr
##First column
if(mod!=0 & div>1){
nr.f<-mod
nc.f<-trunc(div)+1
}else{
if(div<=1){
nc.f<-1
nr.f<-number
}else{
if(mod==0){
nc.f<-div
nr.f<-nr
}
}
}
list(nr=nr.f,nc=nc.f)
}
## Beginning of the function
for(k in 1:(ncol(matrice)-1)){
i=1
j=1
tmp<-0
while(j <= max(matrice[,k])){
if(i==1){
mat<-table(matrice[,k],matrice[,k+1])
number<-which.max(mat)
tmp<-row.col.number(mat,number)
tmp0<-tmp
## Change les indices
if(tmp$nr!=tmp$nc){
find.nc<-which(matrice[,k+1]==tmp$nc)
find.nr<-which(matrice[,k+1]==tmp$nr)
matrice[find.nc,k+1]<-tmp$nr
matrice[find.nr,k+1]<-tmp$nc
}else{}
i=2
}else{
mat<-table(matrice[,k],matrice[,k+1])
mat[tmp0$nr,]<-0
mat[,tmp0$nr]<-0
number<-which.max(mat)
tmp<-row.col.number(mat,number)
## Change les indices
if(tmp$nr!=tmp$nc){
find.nc<-which(matrice[,k+1]==tmp$nc)
find.nr<-which(matrice[,k+1]==tmp$nr)
matrice[find.nc,k+1]<-tmp$nr
matrice[find.nr,k+1]<-tmp$nc
}else{}
tmp0$nr<-c(tmp0$nr,tmp$nr)
}
j=j+1
}
}
matrice
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/pregraphKM.R
|
`prepanel.ordi3d` <-
function(xlim = xlim, ylim = ylim, zlim = zlim, aspect = c(1,1), ...)
{
aspect = c(diff(ylim)/diff(xlim), diff(zlim)/diff(xlim))
prepanel.default.cloud(xlim = xlim, ylim = ylim, zlim = zlim, aspect = aspect, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/prepanel.ordi3d.R
|
`prestondistr` <-
function (x, truncate = -1, ...)
{
fun <- function(par, x, truncate) {
up <- dnorm(x, par[1], par[2], log = TRUE)
dn <- pnorm(truncate, par[1], par[2], lower.tail = FALSE)
-sum(up - log(dn))
}
x <- x[x > 0]
logx <- log2(x)
p <- c(mean(logx), sd(logx))
sol <- optim(p, fun, x = logx, truncate = truncate)
p <- sol$par
area <- pnorm(truncate, p[1], p[2], lower.tail = FALSE)
scale <- length(x)/sqrt(2 * pi)/p[2]/area
p <- c(p, scale)
oct <- as.preston(x, ...)
x <- as.numeric(names(oct))
fit <- p[3] * exp(-(x - p[1])^2/2/p[2]^2)
names(p) <- c("mode", "width", "S0")
out <- list(freq = oct, fitted = fit, coefficients = p)
out$method <- "maximized likelihood to log2 abundances"
class(out) <- "prestonfit"
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/prestondistr.R
|
`prestonfit` <-
function (x, tiesplit = TRUE, ...)
{
x <- as.preston(x, tiesplit = tiesplit)
oct <- as.numeric(names(x))
fit <- glm(x ~ oct + I(oct^2),
family = if (tiesplit) quasipoisson else poisson)
fv <- fitted(fit)
p <- coef(fit)
if (!is.na(p[3]) && p[3] < 0) {
mu <- -p[2]/2/p[3]
sd <- sqrt(-1/2/p[3])
S0 <- exp(p[1] - p[2]^2/4/p[3])
p <- c(mu, sd, S0)
}
else {
p <- rep(NA, 3)
}
names(p) <- c("mode", "width", "S0")
out <- list(freq = unclass(x), fitted = fv, coefficients = p)
out$method = "Poisson fit to octaves"
if(tiesplit)
out$method <- paste("Quasi-", out$method, sep="")
class(out) <- c("prestonfit")
out
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/prestonfit.R
|
`print.CCorA` <-
function(x, ...)
{
cat("\nCanonical Correlation Analysis\n")
cat("\nCall:\n")
cat(deparse(x$call), "\n\n")
out <- structure(rbind(x$Mat.ranks), dimnames = list("Matrix Ranks", c("Y", "X")))
print(out, ...)
cat("\n")
cat("Pillai's trace: ", format(x$Pillai, ...), "\n")
cat("\n")
cat("Significance of Pillai's trace:\n")
cat("from F-distribution: ", format.pval(x$p.Pillai), "\n")
if (x$nperm > 0) {
cat("based on permutations: ")
cat(x$p.perm,"\n")
cat(howHead(x$control), "\n")
}
out <- rbind("Eigenvalues" = x$EigenValues, "Canonical Correlations" = x$CanCorr)
colnames(out) <- colnames(x$Cy)
printCoefmat(out, ...)
cat("\n")
out <- rbind("RDA R squares" = x$RDA.Rsquares, "adj. RDA R squares" = x$RDA.adj.Rsq)
colnames(out) <- c("Y | X", "X | Y")
printCoefmat(out, ...)
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.CCorA.R
|
`print.MOStest` <-
function(x, ...)
{
cat("\nMitchell-Olds and Shaw test\n")
cat("Null: hump of a quadratic linear predictor is at min or max\n")
print(x$family)
print(x$hump)
if (!x$isBracketed)
cat("***** Caution: hump/pit not bracketed by the data ******\n")
cat("\n")
printCoefmat(coef(x), has.Pvalue = TRUE, na.print = "")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.MOStest.R
|
`print.anosim` <-
function (x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\nCall:\n")
cat(deparse(x$call), "\n")
cat("Dissimilarity:", x$dissimilarity,"\n\n")
cat("ANOSIM statistic R: ")
cat(formatC(x$statistic, digits = digits), "\n")
nperm <- x$permutations
if (nperm) {
cat(" Significance:", format.pval(x$signif),
"\n\n")
cat(howHead(x$control))
}
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.anosim.R
|
`print.betadisper` <- function(x, digits = max(3, getOption("digits") - 3),
neigen = 8, ...)
{
## limit number of eignvals to neigen
eig <- eigenvals(x)
nev <- length(eig)
ax.lim <- min(nev, neigen)
##
cat("\n")
writeLines(strwrap("Homogeneity of multivariate dispersions\n",
prefix = "\t"))
cat("\n")
writeLines(strwrap(pasteCall(x$call)))
cat(paste("\nNo. of Positive Eigenvalues:", sum(eig > 0)))
cat(paste("\nNo. of Negative Eigenvalues:", sum(eig < 0)))
cat("\n\n")
type <- ifelse(isTRUE(all.equal(attr(x, "type"), "median")),
"median", "centroid")
writeLines(strwrap(paste0("Average distance to ", type, ":\n")))
print.default(format(x$group.distances, digits = digits), quote = FALSE)
cat("\n")
writeLines(strwrap("Eigenvalues for PCoA axes:"))
if (nev > neigen) {
writeLines(strwrap(paste0("(Showing ", neigen, " of ", nev,
" eigenvalues)")))
}
print.default(format(eig[seq_len(ax.lim)], digits = digits), quote = FALSE)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.betadisper.R
|
`print.bioenv` <-
function (x, ...)
{
cat("\nCall:\n")
cat(deparse(x$call), "\n")
cat("\nSubset of environmental variables with best correlation to community data.\n\n")
cat("Correlations: ", x$method, "\n")
cat("Dissimilarities:", x$index, "\n")
cat("Metric: ", x$metric, "\n\n")
i <- which.max(lapply(x$models, function(tmp) tmp$est))
cat("Best model has", i, "parameters (max.", x$upto, "allowed):\n")
cat(paste(x$names[x$models[[i]]$best], collapse = " "))
cat("\nwith correlation ", x$models[[i]]$est, "\n\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.bioenv.R
|
`print.cca` <-
function (x, digits = max(3, getOption("digits") - 3), ...)
{
writeLines(strwrap(pasteCall(x$call)))
cat("\n")
chi <- c(x$tot.chi, x$pCCA$tot.chi, x$CCA$tot.chi, x$CA$tot.chi)
props <- chi/chi[1]
rnk <- c(NA, x$pCCA$rank, x$CCA$rank, x$CA$rank)
## report no. of real axes in dbrda if any negative eigenvalues
if (inherits(x, "dbrda") &&
(!is.null(x$CCA) && x$CCA$poseig < x$CCA$qrank ||
!is.null(x$CA) && x$CA$poseig < x$CA$rank))
poseig <- c(NA, if (!is.null(x$pCCA)) NA, x$CCA$poseig, x$CA$poseig)
else
poseig <- NULL
tbl <- cbind(chi, props, rnk, poseig)
if (!is.null(x$CA$imaginary.chi))
tbl <- rbind(tbl, c(x$CA$imaginary.chi,
x$CA$imaginary.chi/x$tot.chi,
x$CA$imaginary.rank, NULL))
colnames(tbl) <- c("Inertia", "Proportion", "Rank",
if (!is.null(poseig)) "RealDims")
rn <- c("Total", "Conditional", "Constrained", "Unconstrained",
"Imaginary")
rownames(tbl) <- rn[c(TRUE,!is.null(x$pCCA),
!is.null(x$CCA), !is.null(x$CA),
!is.null(x$CA$imaginary.chi))]
## Remove "Proportion" if only one component
if (is.null(x$CCA) && is.null(x$pCCA))
tbl <- tbl[,-2]
## 'cs' columns before "Rank" are non-integer
cs <- which(colnames(tbl) == "Rank") - 1
printCoefmat(tbl, digits = digits, na.print = "", cs.ind = seq_len(cs))
cat("Inertia is", x$inertia, "\n")
## data used for species scores in db ordination
if (!is.null(x$vdata))
cat("Species scores projected from", sQuote(x$vdata), "\n")
if (!is.null(x$CCA$alias))
cat("Some constraints or conditions were aliased because they were redundant\n")
## Report removed observations and species
if (!is.null(x$na.action))
cat(naprint(x$na.action), "\n")
sp.na <- if (is.null(x$CCA)) attr(x$CA$v, "na.action")
else attr(x$CCA$v, "na.action")
if (!is.null(sp.na))
cat(length(sp.na), "species",
ifelse(length(sp.na)==1, "(variable)", "(variables)"),
"deleted due to missingness\n")
if (!is.null(x$CCA) && x$CCA$rank > 0) {
cat("\nEigenvalues for constrained axes:\n")
print(zapsmall(x$CCA$eig, digits = digits), ...)
}
if (!is.null(x$CA) && x$CA$rank > 0) {
ax.lim <- 8
ax.trig <- 16
cat("\nEigenvalues for unconstrained axes:\n")
if (x$CA$rank > ax.trig) {
print(zapsmall(x$CA$eig[1:ax.lim], digits = digits), ...)
cat("(Showing", ax.lim, "of", x$CA$rank,
"unconstrained eigenvalues)\n")
}
else print(zapsmall(x$CA$eig, digits = digits), ...)
}
cat("\n")
if (inherits(x, c("capscale", "dbrda"))) {
if (!is.null(x$metaMDSdist))
cat("metaMDSdist transformed data:", x$metaMDSdist, "\n\n")
if (!is.null(x$ac))
cat("Constant added to distances:", x$ac, "\n\n")
}
invisible(x)
}
### package klaR has another function called rda(), and to avoid using
### klar:::print.rda instead of delegating to vegan:::print.cca we
### define here a (redundant) print.rda
`print.rda` <-
function(x, ...)
{
## not vegan rda?
if (!("CA" %in% names(x)))
stop(gettextf("%s is not a vegan rda object",
sQuote(deparse(substitute(x)))))
NextMethod("print", x, ...)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.cca.R
|
print.commsim <- function(x, ...) {
cat("An object of class", dQuote(class(x)[1L]), "\n")
isSeq <- ifelse(x$isSeq, "sequential", "non-sequential")
if(x$binary)
kind <- "binary"
else
kind <- ifelse(x$mode == "integer", "count", "abundance")
cat(sQuote(x$method), " method (",
kind, ", ", isSeq, ", ", x$mode, " mode)\n\n", sep="")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.commsim.R
|
`print.decorana` <-
function (x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\nCall:\n")
cat(deparse(x$call), "\n\n")
cat(ifelse(x$ira, "Orthogonal", "Detrended"), "correspondence analysis")
cat(ifelse(!x$ira, paste(" with ", x$mk, " segments.\n",
sep = ""), ".\n"))
if (x$iresc) {
cat("Rescaling of axes with", x$iresc, "iterations")
if (x$short)
cat(", and shortest axis rescaled", x$short)
cat(".\n")
}
if (!is.null(x$v))
cat("Downweighting of rare species from fraction 1/", x$fraction, ".\n", sep="")
if (!is.null(x$before)) {
cat("Piecewise transformation of above-zero abundances:")
print(as.data.frame(rbind(before = x$before, after = x$after),
optional=TRUE))
}
cat("Total inertia (scaled Chi-square):", round(x$totchi, digits), "\n")
axlen <- apply(x$rproj, 2, function(z) diff(range(z)))
cat("\n")
print(rbind("Eigenvalues" = x$evals,
"Additive Eigenvalues" = x$evals.ortho,
"Decorana values" = x$evals.decorana,
"Axis lengths" = axlen), digits = digits)
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.decorana.R
|
"print.envfit" <-
function(x, ...)
{
if (!is.null(x$vectors)) {
cat("\n***VECTORS\n\n")
print(x$vectors)
}
if (!is.null(x$factors)) {
cat("\n***FACTORS:\n\n")
print(x$factors)
}
if (!is.null(x$na.action))
cat("\n", naprint(x$na.action), "\n", sep="")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.envfit.R
|
`print.factorfit` <-
function (x, ...)
{
cat("Centroids:\n")
printCoefmat(x$centroids, tst.ind = 1:ncol(x$centroids), na.print = "", ...)
cat("\nGoodness of fit:\n")
out <- cbind(r2 = x$r, "Pr(>r)" = x$pvals)
if (x$permutations) {
printCoefmat(out, has.Pvalue = TRUE, ...)
cat(howHead(x$control))
}
else printCoefmat(out, na.print = "", ...)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.factorfit.R
|
`print.fisherfit` <-
function (x, ...)
{
cat("\nFisher log series model\n")
cat("No. of species:", sum(x$fisher), "\n")
cat("Fisher alpha: ", x$estimate, "\n\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.fisherfit.R
|
`print.isomap` <-
function (x, ...)
{
cat("\nIsometric Feature Mapping (isomap)\n\n")
cat("Call:\n")
cat(deparse(x$call), "\n\n")
cat("Distance method:", x$method, "\n")
cat("Criterion:", x$criterion, "=", x$critval, "\n")
if(!is.null(x$take))
cat("Data were fragmented, analysed", sum(x$take), "of", length(x$take), "points\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.isomap.R
|
`print.mantel` <-
function (x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\n")
if (inherits(x, "mantel.partial"))
cat("Partial ")
cat("Mantel statistic based on", x$method, "\n")
cat("\nCall:\n")
cat(deparse(x$call), "\n\n")
cat("Mantel statistic r: ")
cat(formatC(x$statistic, digits = digits), "\n")
nperm <- x$permutations
if (nperm) {
cat(" Significance:", format.pval(x$signif),
"\n\n")
out <- quantile(x$perm, c(0.9, 0.95, 0.975, 0.99), na.rm = TRUE)
cat("Upper quantiles of permutations (null model):\n")
print(out, digits = 3)
cat(howHead(x$control))
}
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.mantel.R
|
'print.mantel.correlog' <- function(x, ...)
{
cat('\nMantel Correlogram Analysis\n')
cat('\nCall:\n','\n')
cat(deparse(x$call),'\n')
cat('\n')
printCoefmat(x$mantel.res, P.values=TRUE, signif.stars=TRUE, Pvalues = TRUE)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.mantel.correlog.R
|
`print.metaMDS` <-
function (x, ...)
{
cat("\nCall:\n")
cat(deparse(x$call), "\n\n")
if (x$engine == "monoMDS")
cat(x$model, "Multidimensional Scaling using monoMDS\n\n")
else if (x$engine == "isoMDS")
cat("non-metric Multidimensional Scaling using isoMDS (MASS package)\n\n")
cat("Data: ", x$data, "\n")
cat("Distance:", x$distance, "\n\n")
cat("Dimensions:", x$ndim, "\n")
cat("Stress: ", x$stress, "\n")
if (inherits(x, "monoMDS")) {
cat("Stress type", x$isform)
if(x$model != "linear")
cat(", ", c("weak", "strong")[x$ities], " ties", sep = "")
cat("\n")
}
if (x$converged) {
cat(sprintf(ngettext(x$converged,
"Best solution was repeated %d time in %d tries\n",
"Best solution was repeated %d times in %d tries\n"),
x$converged, x$tries))
} else {
cat("Best solution was not repeated after", x$tries, "tries\n")
}
cat("The best solution was from try", x$bestry)
if (x$bestry == 0)
cat(" (metric scaling or null solution)\n")
else
cat(" (random start)\n")
z <- x$points
scal <- c(if (attr(z, "centre")) "centring",
if (attr(z, "pc")) "PC rotation",
if (attr(z, "halfchange")) "halfchange scaling")
if (!length(scal))
scal <- "as is"
cat("Scaling:", paste(scal, collapse = ", "), "\n")
if (all(is.na(x$species))) {
cat("Species: scores missing\n")
} else {
spattr <- attr(x$species, "shrinkage")
spdata <- attr(x$species, "data")
if (is.null(spdata))
spdata <- x$data
if (is.null(spattr))
cat("Species: non-expanded scores ")
else
cat("Species: expanded scores ")
cat("based on", sQuote(spdata), "\n")
}
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.metaMDS.R
|
### Method functions for monoMDS objects
`print.monoMDS` <-
function(x, ...)
{
cat("\nCall:\n")
cat(deparse(x$call), "\n\n")
modlab <- switch(x$model,
global = "Non-metric",
local = "Local non-metric",
linear = "Linear",
hybrid = "Hybrid")
cat(paste(modlab, "Multidimensional Scaling\n\n"))
cat(x$nobj, "points")
cat(", dissimilarity", sQuote(x$distmethod))
if (!is.null(x$distcall))
cat(", call", sQuote(x$distcall))
cat("\n\n")
cat("Dimensions:", x$ndim, "\n")
cat("Stress: ", x$stress, "\n")
cat("Stress type", x$isform)
if (x$model != "linear")
cat(", ", c("weak", "strong")[x$ities], " ties", sep = "")
cat("\n")
cat("Scores ")
if (x$iscal == 1)
cat("scaled to unit root mean square")
else
cat("unscaled")
if (attr(x$points, "pc"))
cat(", rotated to principal components")
cat("\n")
stoplab <- switch(x$icause,
"Maximum number of iterations (maxit) reached",
"Stress nearly zero (< smin)",
"Stress nearly unchanged (ratio > sratmax)",
"Scale factor of gradient nearly zero (< sfgrmin)")
cat("Stopped after ", x$iters, " iterations: ", stoplab, "\n", sep="")
invisible(x)
}
`scores.monoMDS` <-
function(x, choices = NA, ...)
{
if (any(is.na(choices)))
x$points
else {
choices <- choices[choices <= x$ndim]
x$points[, choices, drop = FALSE]
}
}
`plot.monoMDS` <-
function(x, choices = c(1,2), type = "t", ...)
{
ordiplot(x, display = "sites", choices = choices, type = type, ...)
}
`points.monoMDS` <-
function(x, choices = c(1,2), select, ...)
{
x <- scores(x, choices = choices)
if (!missing(select))
x <- .checkSelect(select, x)
points(x, ...)
invisible()
}
`text.monoMDS` <-
function(x, labels, choices = c(1,2), select, ...)
{
x <- scores(x, choices = choices)
if (!missing(labels))
rownames(x) <- labels
if (!missing(select))
x <- .checkSelect(select, x)
text(x, labels = rownames(x), ...)
invisible()
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.monoMDS.R
|
"print.mrpp" <-
function (x, digits = max(3, getOption("digits") - 3), ...)
{
### A print function for mrpp objects
### x -- An object of class "mrpp."
#### cat = print
cat("\nCall:\n")
cat(deparse(x$call), "\n\n")
cat("Dissimilarity index:", x$distance, "\n")
cat("Weights for groups: ", switch(x$weight.type, "n", "n-1", "n(n-1)", "n(n-1)/2"), "\n\n")
cat("Class means and counts:\n\n")
print(noquote(rbind("delta" = formatC(x$classdelta, digits = digits),
"n" = formatC(x$n, digits=0))))
cat("\n")
if (!is.na(x$CS)) {
cat("Classification strength: ")
cat(formatC(x$CS, digits = digits), "\n")
}
cat("Chance corrected within-group agreement A: ")
if (!is.na(x$A))
cat(formatC(x$A, digits = digits), "\n")
else
cat("NA\n")
cat("Based on observed delta", formatC(x$delta), "and expected delta",
formatC(x$E.delta),"\n\n")
nperm <- x$permutations
if (nperm) {
cat("Significance of delta:", format.pval(x$Pvalue),
"\n")
}
cat(howHead(x$control))
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.mrpp.R
|
`print.mso` <-
function(x, digits = max(3, getOption("digits") - 3), ...)
{
NextMethod("print", x, digits = digits, ...)
cat("mso variogram:\n\n")
print(x$vario, digits = digits, ...)
if(!is.null(attr(x$vario, "control")))
cat("\n", howHead(attr(x$vario, "control")), "\n", sep="")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.mso.R
|
"print.nestedchecker" <-
function(x, ...)
{
cat("Checkerboard Units :", format(x$statistic), "\n")
cat("C-score (species mean):", format(x$C.score), "\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.nestedchecker.R
|
"print.nesteddisc" <-
function(x, ...)
{
cat("nestedness discrepancy:", x$statistic, "\n")
if(x$ties)
cat("There are tied column frequencies: result can depend on input order\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.nesteddisc.R
|
"print.nestedn0" <-
function(x, ...)
{
cat("Nestedness index N0:", format(x$statistic), "\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.nestedn0.R
|
`print.nestednodf` <-
function(x, ...)
{
cat("N columns :", format(x$statistic["N.columns"], ...), "\n")
cat("N rows :", format(x$statistic["N.rows"], ...), "\n")
cat("NODF :", format(x$statistic["NODF"], ...), "\n")
cat("Matrix fill:", format(x$fill, ...), "\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.nestednodf.R
|
"print.nestedtemp" <-
function(x, ...)
{
cat("nestedness temperature:", format(x$statistic, ...), "\n")
cat("with matrix fill", format(x$fill, ...), "\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.nestedtemp.R
|
print.nullmodel <- function(x, ...) {
isSeq <- ifelse(x$commsim$isSeq, "sequential", "non-sequential")
if (x$commsim$binary)
kind <- "binary"
else
kind <- ifelse(x$commsim$mode == "integer", "count", "abundance")
cat("An object of class", dQuote(class(x)[1L]), "\n")
cat(sQuote(x$commsim$method), " method (",
kind, ", ", isSeq, ")\n", sep="")
cat(x$nrow, "x", x$ncol, "matrix\n")
if (x$commsim$isSeq)
cat("Iterations =", x$iter, "\n\n") else cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.nullmodel.R
|
`print.oecosimu` <-
function(x, ...)
{
xx <- x ## return unmodified input object
attr(x$oecosimu$method, "permfun") <- NULL
cat(as.character(attr(x,"call")[[1]]), "object\n\n")
writeLines(strwrap(pasteCall(attr(x, "call"))))
cat("\n")
cat("nullmodel method", sQuote(x$oecosimu$method), "with",
ncol(x$oecosimu$simulated), "simulations\n")
if (length(att <- attributes(x$oecosimu$simulated)) > 1) {
att$dim <- NULL
cat("options: ", paste(names(att), att, collapse=", "))
}
alt.char <- switch(x$oecosimu$alternative,
two.sided = "less or greater than",
less = "less than",
greater = "greater than")
cat("\nalternative hypothesis: statistic is", alt.char, "simulated values")
## dim attribute is always there, but print all others
cat("\n\n")
if (!inherits(x, c("adipart", "hiersimu", "multipart")) &&
!inherits(x$statistic, c("numeric", "list"))) {
print(x$statistic)
cat("\n")
}
probs <- switch(x$oecosimu$alternative,
two.sided = c(0.025, 0.5, 0.975),
greater = c(0.5, 0.95),
less = c(0.05, 0.5))
qu <- apply(x$oecosimu$simulated, 1, quantile, probs=probs, na.rm = TRUE)
m <- cbind("statistic" = x$oecosimu$statistic,
"SES" = x$oecosimu$z, "mean" = x$oecosimu$means, t(qu),
"Pr(sim.)"=x$oecosimu$pval)
printCoefmat(m, cs.ind = 3:(ncol(m)-1), ...)
if (any(is.na(x$oecosimu$simulated))) {
nacount <- rowSums(is.na(x$oecosimu$simulated))
cat("\nNumber of NA cases removed from simulations:\n",
nacount, "\n")
}
invisible(xx)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.oecosimu.R
|
## S3 print method for permat
`print.permat` <-
function(x, digits=3, ...)
{
cat("Object of class 'permat' with ", attr(x, "times"), " simulations\n", sep="")
cat("\nMatrix type:", attr(x, "mtype"), "\nPermutation type:", attr(x, "ptype"))
cat("\nMethod: ", attr(x, "method"), sep = "")
if (attr(x, "ptype") == "swap") {
if (!is.na(attr(x, "burnin")))
cat(", burnin: ", attr(x, "burnin"), sep = "")
if (!is.na(attr(x, "thin")))
cat(", thin: ", attr(x, "thin"), sep = "")
}
cat("\nRestricted:", attr(x, "is.strat"), "\nFixed margins:", attr(x, "fixedmar"))
if (!is.na(attr(x, "shuffle"))) {
if (attr(x, "shuffle")=="ind") cat("\nIndividuals")
if (attr(x, "shuffle")=="samp") cat("\nSamples")
if (attr(x, "shuffle")=="both") cat("\nIndividuals and samples")
cat(" are shuffled")
}
cat("\n")
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.permat.R
|
`print.permutest.betadisper` <- function(x, digits = max(getOption("digits") - 2, 3),
...)
{
## uses code from stats:::print.anova by R Core Development Team
cat("\n")
writeLines(strwrap("Permutation test for homogeneity of multivariate dispersions\n"))
##cat("\n")
cat(howHead(x$control))
nc <- dim(x$tab)[2]
cn <- colnames(x$tab)
has.P <- substr(cn[nc], 1, 3) == "Pr("
zap.i <- 1:(if (has.P)
nc - 1
else nc)
i <- which(substr(cn, 2, 7) == " value")
i <- c(i, which(!is.na(match(cn, "F"))))
if (length(i))
zap.i <- zap.i[!(zap.i %in% i)]
tst.i <- i
if (length(i <- grep("Df$", cn)))
zap.i <- zap.i[!(zap.i %in% i)]
if (length(i <- grep("N.Perm$", cn)))
zap.i <- zap.i[!(zap.i %in% i)]
cat("\nResponse: Distances", sep = "\n")
printCoefmat(x$tab, digits = digits,
signif.stars = getOption("show.signif.stars"),
has.Pvalue = has.P, P.values = has.P, cs.ind = NULL,
zap.ind = zap.i, tst.ind = tst.i, na.print = "", ...)
if(!is.null(x$pairwise)) {
cat("\nPairwise comparisons:", sep = "\n")
writeLines(strwrap("(Observed p-value below diagonal,\npermuted p-value above diagonal)\n"))
n.grp <- length(x$groups)
mat <- matrix(NA, ncol = n.grp, nrow = n.grp)
colnames(mat) <- rownames(mat) <- x$groups
mat[lower.tri(mat)] <- x$pairwise$observed
mat <- t(mat)
mat[lower.tri(mat)] <- x$pairwise$permuted
printCoefmat(t(mat), na.print = "", digits = digits)
}
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.permutest.betadisper.R
|
`print.permutest.cca` <-
function (x, ...)
{
EPS <- sqrt(.Machine$double.eps)
cat("\nPermutation test for", x$method, "under", x$model, "model", "\n\n")
cat(howHead(x$control), "\n")
writeLines(strwrap(pasteCall(x$testcall, prefix = "Model:")))
Pval <- (colSums(sweep(x$F.perm, 2, x$F.0 - EPS, ">=")) + 1)/(x$nperm + 1)
cat("Permutation test for ")
if (x$first)
cat("first constrained eigenvalue\n")
else if (length(x$df) <= 2)
cat("all constrained eigenvalues\n")
else
cat("sequential contrasts\n")
anotab <- data.frame(x$df, x$chi, c(x$F.0, NA), c(Pval, NA))
colnames(anotab) <- c("Df", "Inertia", "F", "Pr(>F)")
rownames(anotab) <- c(x$termlabels, "Residual")
class(anotab) <- c("anova", "data.frame")
print(anotab)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.permutest.cca.R
|
`print.poolaccum` <-
function(x, ...)
{
rownames(x$means) <- rep("", nrow(x$means))
print(x$means, ...)
invisible(x)
}
|
/scratch/gouwar.j/cran-all/cranData/vegan/R/print.poolaccum.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.