home *** CD-ROM | disk | FTP | other *** search
/ Big Green CD 8 / BGCD_8_Dev.iso / NEXTSTEP / UNIX / Educational / R-0.49-MI / R-0.49-I / library / base < prev    next >
Encoding:
Text File  |  1997-09-14  |  175.6 KB  |  6,323 lines

  1. abline <-
  2. function(a=NULL, b=NULL, h=NULL, v=NULL, reg=NULL, coef=NULL,
  3.     col=par("col"), lty=par("lty"), ...)
  4. {
  5.     if(!is.null(reg)) a <- reg
  6.     if(!is.null(a) && is.list(a)) {
  7.         temp <- as.vector(coefficients(a))
  8.         if(length(temp) == 1) {
  9.             a <- 0
  10.             b <- temp
  11.         }
  12.         else {
  13.             a <- temp[1]
  14.             b <- temp[2]
  15.         }
  16.     }
  17.     if(!is.null(coef)) {
  18.         a <- coef[1]
  19.         b <- coef[2]
  20.     }
  21.     .Internal(abline(a, b, h, v, col, lty, ...))
  22.     invisible()
  23. }
  24. aperm <- function(a, perm, resize=TRUE) {
  25.     if (missing(perm))
  26.         perm<-(length(dim(a)):1)
  27.     else {
  28.         if(length(perm) != length(dim(a)))
  29.             stop("perm has incorrect length")
  30.         if(!all(sort(perm)==1:length(perm)))
  31.             stop("perm is not a permutation")
  32.     }
  33.     .Internal(aperm(a,perm,resize))
  34. }
  35. append <- function (x, values, after = length(x)) 
  36. {
  37.         lengx <- length(x)
  38.         if (after <= 0) 
  39.                 c(values, x)
  40.         else if (after >= lengx) 
  41.                 c(x, values)
  42.         else c(x[1:after], values, x[(after + 1):lengx])
  43. }
  44. "apply"<-
  45. function(X, MARGIN, FUN, ...)
  46. {
  47.     # ENSURE THAT FUN IS A FUNCTION
  48.     if(is.character(FUN))
  49.         FUN <- get(FUN, mode = "function")
  50.     else if(mode(FUN) != "function") {
  51.         f <- substitute(FUN)
  52.         if(is.name(f))
  53.             FUN <- get(as.character(f), mode = "function")
  54.         else stop(paste("\"", f, "\" is not a function", sep = ""))
  55.     }
  56.     # ENSURE THAT X IS AN ARRAY OBJECT
  57.     d <- dim(X)
  58.     dl <- length(d)
  59.     ds <- 1:length(d)
  60.     if(dl == 0)
  61.         stop("dim(X) must have a positive length")
  62.     if(length(class(X)) > 0)
  63.         X <- if(dl == 2) as.matrix(X) else as.array(X)
  64.     dn <- dimnames(X)
  65.     # EXTRACT THE MARGINS AND ASSOCIATED DIMNAMES
  66.     s.call <- (1:length(d))[-MARGIN]
  67.     s.ans <- (1:length(d))[MARGIN]
  68.     d.call <- d[-MARGIN]
  69.     d.ans <- d[MARGIN]
  70.     dn.call <- dn[-MARGIN]
  71.     dn.ans <- dn[MARGIN]
  72.     # dimnames(X) <- NULL
  73.     # DO THE CALLS
  74.     newX <- aperm(X, c(s.call, s.ans))
  75.     dim(newX) <- c(prod(d.call), prod(d.ans))
  76.     d2 <- dim(newX)[2]
  77.     ans <- vector("list", d2)
  78.     for(i in 1:d2)
  79.         ans[[i]] <- FUN(array(newX[,i], d.call, dn.call), ...)
  80.     # ANSWER DIMS AND DIMNAMES
  81.     ans.names <- names(ans[[1]])
  82.     ans.list <- is.recursive(ans[[1]])
  83.     ans.length <- length(ans[[1]])
  84.     if(!ans.list)
  85.         ans.list <- any(unlist(lapply(ans, length)) != ans.length)
  86.     if(!ans.list)
  87.         ans <- unlist(ans, recursive = F)
  88.     if(length(MARGIN) == 1 && length(ans) == d2) {
  89.         if(length(dn.ans[[1]]) > 0)
  90.             names(ans) <- dn.ans[[1]]
  91.         else names(ans) <- NULL
  92.         return(ans)
  93.     }
  94.     else if(length(ans) == d2)
  95.         return(array(ans, d.ans, dn.ans))
  96.     else if(length(ans) > 0 && length(ans) %% d2 == 0) {
  97.         if(is.null(dn.ans))
  98.             return(array(ans, c(length(ans)/d2, d[MARGIN])))
  99.         else return(array(ans, c(length(ans)/d2, d.ans),
  100.                 c(list(ans.names), dn.ans)))
  101.     }
  102.     else return(ans)
  103. }
  104. approx <- function(x, y, xout, method="lines", n=50, rule=1) {
  105.     if( !is.numeric(x) || !is.numeric(y) )
  106.         stop("approx: x and y must be numeric")
  107.     if(length(x) != length(y)) stop("x and y must have equal lengths")
  108.     ok <- !(is.na(x) | is.na(y))
  109.     x <- x[ok]
  110.     y <- y[ok]
  111.     if(length(x) < 2) stop("approx requires at least two values to interpolate")
  112.     o <- order(x)
  113.     x <- x[o]
  114.     y <- y[o]
  115.     if(missing(xout)) {
  116.         if(n <= 0) stop("approx requires n >= 1")
  117.         xout <- seq(x[1], x[length(x)], length=n)
  118.     }
  119.     if(rule == 1) {
  120.         low <- y[1]
  121.         high <- y[length(x)]
  122.     }
  123.     else if(rule == 2){
  124.         low <- NA
  125.         high <- low
  126.     }
  127.     else stop("invalid extrapolation rule in approx")
  128.     y<-.C("approx", as.double(x), as.double(y), length(x), xout=as.double(xout), length(xout), as.double(low), as.double(high))$xout
  129.     return(list(x=xout,y=y))
  130. }
  131. approxfun <- function(x, y, method="lines", rule=1) {
  132.     if(length(x) != length(y)) stop("x and y must have equal lengths")
  133.     if( !is.numeric(x) || !is.numeric(y) )
  134.         error("approxfun: x and y must be numeric")
  135.     ok <- !(is.na(x) | is.na(y))
  136.     x <- x[ok]
  137.     y <- y[ok]
  138.     if(length(x) < 2) stop("approx requires at least two values to interpolate")
  139.     o <- order(x)
  140.     x <- x[o]
  141.     y <- y[o]
  142.     if(rule == 1) {
  143.         low <- y[1]
  144.         high <- y[length(x)]
  145.     }
  146.     else if(rule == 2){
  147.         low <- as.double(NA)
  148.         high <- low
  149.     }
  150.     rm(method, rule)
  151.     function(v)
  152.         .C("approx", as.double(x), as.double(y), length(x), xout=as.double(v), length(v), low, high)$xout
  153. }
  154. array <- function(data = NA, dim = length(data), dimnames = NULL)
  155. {
  156.     data <- as.vector(data)
  157.     vl <- prod(dim)
  158.     if( length(data) != vl  ) {
  159.         t1 <- ceiling(vl/length(data))
  160.         data <- rep(data,t1)
  161.         if( length(data) != vl )
  162.             data <- data[1:vl]
  163.     }
  164.     dim(data) <- dim
  165.     if(is.list(dimnames))
  166.         dimnames(data) <- dimnames
  167.     data
  168. }
  169. arrows <- function(x0, y0, x1, y1, length=0.25, angle=30, code=2,
  170.         col=par("fg"), lty=NULL, xpd=FALSE) {
  171.     .Internal(arrows(
  172.         x0,
  173.         y0,
  174.         x1,
  175.         y1,
  176.         length=length,
  177.         angle=angle,
  178.         code=code,
  179.         col=col,
  180.         lty=lty,
  181.         xpd=xpd))
  182. }
  183. as.logical <- function(x) .Internal(as.vector(x,"logical"))
  184. as.integer <- function(x) .Internal(as.vector(x,"integer"))
  185. as.real <- function(x) .Internal(as.vector(x,"real"))
  186. as.complex <- function(x) .Internal(as.vector(x, "complex"))
  187. as.double <- function(x) .Internal(as.vector(x,"real"))
  188. as.single <- function(x) 
  189. {
  190.     warning("type single is not supported in R")
  191.     .Internal(as.vector(x,"real"))
  192. }
  193. as.character <- function(x) .Internal(as.vector(x,"character"))
  194. as.list <- function(x) .Internal(as.vector(x,"list"))
  195. as.vector <- function(x, mode="any") .Internal(as.vector(x,mode))
  196. as.matrix <- function(x)
  197. {
  198.     UseMethod("as.matrix")
  199. }
  200. as.matrix.default <- function(x)
  201. {
  202.     if( is.matrix(x) )
  203.         x
  204.     else
  205.         array(x, c(length(x),1), if(!is.null(names(x))) list(names(x), NULL) else NULL)
  206. }
  207. as.matrix.data.frame <- function(x)
  208. {
  209.     y <- .Internal(as.matrix.data.frame(x))
  210.     dimnames(y) <- dimnames(x)
  211.     y
  212. }
  213. as.null <- function(x) NULL
  214. as.function <- function(x) stop("mode function cannot be assigned")
  215. as.array <- function(x)
  216. {
  217.     if( is.array(x) )
  218.         return(x)
  219.     dim(x) <-length(x)
  220.     return(x)
  221. }
  222. as.name <- function(x) .Internal(as.name(x))
  223. # as.call <- function(x) stop("type call cannot be assigned")
  224. as.numeric <- as.double
  225. as.qr <- function(x) stop("you cannot be serious")
  226. as.ts <- function(x) if(is.ts(x)) x else ts(x)
  227. as.formula <- function(object) 
  228.     if(inherits(object, "formula")) object else formula(object)
  229. assign <- 
  230. function(x, value, envir=sys.frame(sys.parent()), inherits=FALSE, 
  231. immediate=TRUE)
  232. .Internal(assign(x,value,envir,inherits))
  233. attach <- function(x, pos=2) 
  234.     .Internal(attach(x, pos, deparse(substitute(x))))
  235. detach <- function(name, pos=2)
  236. {
  237.     if(!missing(name)) {
  238.         name <- substitute(name)
  239.         if(!is.character(name))
  240.             name <- deparse(name)
  241.         pos <- match(name, search())
  242.         if(is.na(pos))
  243.             stop("invalid name")
  244.     }
  245.     .Internal(detach(pos))
  246. }
  247. "objects" <-
  248. function (name, pos = -1, envir = NULL, all.files = FALSE, pattern) 
  249. {
  250.         if (!missing(name)) {
  251.                 name <- substitute(name)
  252.                 if (!is.character(name)) 
  253.                         name <- deparse(name)
  254.                 pos <- match(name, search())
  255.                 if (is.na(pos)) 
  256.                         stop("invalid name")
  257.         }
  258.         else if (!missing(pos)) {
  259.                 if (pos < 1 || pos > length(search())) 
  260.                         stop("invalid pos value")
  261.         }
  262.         else if (!missing(envir)) {
  263.                 pos <- 0
  264.         }
  265.         else {
  266.                 pos <- -1
  267.         }
  268.         all.files <- .Internal(ls(pos, envir, all.files))
  269.     if(!missing(pattern))
  270.         grep(pattern, all.files, value = TRUE)
  271.     else all.files
  272. }
  273. ls <- objects
  274. # Average a vector over the levels of a factor.
  275. ave  <-  function (x, ...) 
  276. {
  277.     l <- list(...)
  278.     if (is.null(l)) {
  279.         x[] <- mean(x)
  280.     }
  281.     else {
  282.         g <- 1
  283.         nlv <- 1
  284.         for (i in 1:length(l)) {
  285.             l[[i]] <- as.factor(l[[i]])
  286.             g <- g + nlv * (as.numeric(l[[i]]) - 1)
  287.             nlv <- nlv * length(levels(l[[i]]))
  288.         }
  289.         x[] <- lapply(split(x, g), mean)[g]
  290.     }
  291.     x
  292. }
  293. "axis" <-
  294. function (which, at, labels = TRUE, ...) 
  295. {
  296.     if (which%%2 == 1) {
  297.         axp <- par("xaxp")
  298.         usr <- par("usr")[1:2]
  299.         log <- par("xlog")
  300.     }
  301.     else {
  302.         axp <- par("yaxp")
  303.         usr <- par("usr")[3:4]
  304.         log <- par("ylog")
  305.     }
  306.     if (missing(at)) {
  307.         if (log) {
  308.             if (usr[2] < usr[1] + 1) {
  309.                 at <- seq(axp[1], axp[2], length = axp[3] + 1)
  310.             }
  311.             else {
  312.                 p1 <- ceiling(min(usr))
  313.                 p2 <- floor(max(usr))
  314.                 if (p2 - p1 < 2) {
  315.                  at <- c(1, 2, 5) * 10^rep(p1:p2, rep(3, p2 - p1 + 1))
  316.                  at <- at[10^usr[1] <= at & at < 10^usr[2]]
  317.                 }
  318.                 else at <- 10^seq(p1, p2, by = 1)
  319.             }
  320.         }
  321.         else at <- seq(axp[1], axp[2], length = axp[3] + 1)
  322.         ind <- rep(TRUE, length(at))
  323.     }
  324.     else {
  325.         ind <- (usr[1] <= at & at <= usr[2])
  326.     }
  327.     if (is.logical(labels)) {
  328.         if (labels) {
  329.             if (!log) 
  330.                 at[abs(at/(max(at) - min(at))) < 0.001] <- 0
  331.             labels <- format(at, trim = T)
  332.         }
  333.         else labels <- rep("", length(at))
  334.     }
  335.     else labels <- format(labels, trim = T)
  336.     .Internal(axis(which, as.double(at[ind]), labels[ind], ...))
  337. }
  338. backsolve <-
  339. function(r, x, k=ncol(r))
  340. {
  341.     r <- as.matrix(r)
  342.     x <- as.matrix(x)
  343.     if(k <= 0 || nrow(x) != k) stop("invalid parameters in backsolve")
  344.     z <- .Fortran("bkslv",
  345.         as.double(r),
  346.         nrow(r),
  347.         as.integer(k),
  348.         as.double(x),
  349.         as.integer(k),
  350.         y=matrix(0, k, ncol(x)),
  351.         as.integer(1),
  352.         info=integer(1),
  353.         DUP=FALSE)
  354.     if(z$info != 0) stop("singular matrix in backsolve")
  355.     z$y
  356. }
  357. "barplot" <-
  358. function (height, names.arg, col=NULL, border=par("fg"),
  359.     beside=FALSE, space=0.2, legend.text,
  360.     main=NULL, xlab=NULL, ylab=NULL, xlim, ylim, ...)
  361. {
  362.     opar <- par(yaxs="i", xpd=TRUE)
  363.     on.exit(par(opar))
  364.     if (is.matrix(height)) {
  365.         if (beside) {
  366.             delta <- 0.5 * (1 - space)
  367.             if (missing(xlim))
  368.                 xlim <- c(0, ncol(height)) + 0.5
  369.             if (missing(ylim))
  370.                 ylim <- range(-0.01, height)
  371.             plot.new()
  372.                         plot.window(xlim, ylim, log = "")
  373.             for (i in 1:ncol(height)) {
  374.                 xx <- seq(i-delta, i+delta, length=nrow(height)+1)
  375.                 xl <- xx[1:nrow(height)]
  376.                 xr <- xx[1:nrow(height)+1]
  377.                 rect(xl, 0, xr, height[,i], col=col, xpd=TRUE)
  378.             }
  379.         }
  380.         else {
  381.             delta <- 0.5 * (1 - space)
  382.             nheight <- rbind(0, apply(height, 2, cumsum))
  383.             if (missing(xlim)) 
  384.                 xlim <- c(0, ncol(height)) + 0.5
  385.             if (missing(ylim)) 
  386.                 ylim <- range(-0.01, nheight)
  387.             plot.new()
  388.             plot.window(xlim, ylim, log = "")
  389.             for (i in 1:ncol(height))
  390.                 rect(i - delta, nheight[-1, i],
  391.                      i + delta, nheight[1:nrow(height), i],
  392.                      col = col, xpd=TRUE)
  393.         }
  394.         if(missing(names.arg))
  395.             names.arg <- dimnames(height)[[2]]
  396.         if(!is.null(names.arg)) {
  397.             if(length(names.arg) != ncol(height))
  398.                 stop("incorrect number of names")
  399.             for(i in 1:length(names.arg))
  400.             axis(1, at=1:length(names.arg),
  401.                 labels=names.arg, lty=0)
  402.         }
  403.     }
  404.     else {
  405.         delta <- 0.5 * (1 - space)
  406.         if (missing(xlim)) 
  407.             xlim <- c(0, length(height)) + 0.5
  408.         if (missing(ylim)) 
  409.             ylim <- range(-0.01, height)
  410.         plot.new()
  411.         plot.window(xlim, ylim, log = "")
  412.         rect(1:length(height) - delta, 0,
  413.              1:length(height) + delta, height, col, xpd=TRUE)
  414.         if(missing(names.arg))
  415.             names.arg <- names(height)
  416.         if(!is.null(names.arg))
  417.             for(i in 1:length(names.arg))
  418.             axis(1,1:length(height), labels=names.arg, lty=0)
  419.     }
  420.     if(!missing(legend.text) && !missing(col)) {
  421.         xy <- par("usr")
  422.         legend(xy[2]-xinch(0.1),xy[4]-yinch(0.1),
  423.             legend=rev(legend.text), fill=rev(col),
  424.             xjust=1, yjust=1)
  425.     }
  426.     title(main=main, xlab=xlab, ylab=ylab, ...)
  427.     axis(2)
  428. }
  429. box <- function(lty="solid", ...)
  430.     .Internal(box(lty=lty, ...))
  431. boxplot <- function(x, ..., range=1.5, width=NULL, varwidth=FALSE,
  432.     notch=FALSE, names, data=sys.frame(sys.parent()),
  433.     plot=TRUE, border=par("fg"), col=NULL, log="", pars=NULL)
  434. {
  435.     if(is.language(x)) {
  436.         if(length(x) == 3 && deparse(x[[1]]) == '~') {      
  437.             groups <- eval(x[[3]], data)
  438.             x <- eval(x[[2]], data)
  439.             groups <- split(x, groups)
  440.         }
  441.         else stop("invalid first argument")
  442.         apars <- list(...)
  443.         pars <- c(apars[named.elements(apars)], pars)
  444.     }
  445.     else {
  446.         groups <- list(x, ...)
  447.         n <- named.elements(groups)
  448.         pars <- c(groups[n], pars)
  449.         groups[n] <- NULL
  450.         if(length(groups)==1 && is.list(x))
  451.             groups <- x
  452.     }
  453.     n <- length(groups)
  454.     if(!missing(names)) attr(groups, "names") <- names
  455.     else if(is.null(attr(groups, "names"))) attr(groups, "names") <- 1:n
  456.     for(i in 1:n)
  457.         groups[i] <- list(boxplot.stats(groups[[i]], range))
  458.     if(plot) {
  459.         bxp(groups, width, varwidth=varwidth, notch=notch,
  460.             border=border, col=col, log=log, pars=pars)
  461.         invisible(groups)
  462.     }
  463.     else groups
  464. }
  465. boxplot.stats <- function(x, coef)
  466. {
  467.     nna <- !is.na(x)
  468.     n <- length(nna)
  469.     stats <- fivenum(x, na.rm=TRUE)
  470.     iqr <- diff(stats[c(2, 4)])
  471.     out <- x < (stats[2]-coef*iqr) | x > (stats[4]+coef*iqr)
  472.     if(coef > 0) stats[c(1, 5)] <- range(x[!out], na.rm=TRUE)
  473.     conf <- stats[3]+c(-1.58, 1.58)*diff(stats[c(2, 4)])/sqrt(n)
  474.     list(stats=stats, n=n, conf=conf, out=x[out&nna])
  475. }
  476. bxp <- function(z, notch=FALSE, width=NULL, varwidth=FALSE,
  477.     border=par("fg"), col=NULL, log="", pars=NULL, ...)
  478. {
  479.     bplt <- function(x, wid, stats, out, conf, notch, border, col)
  480.     {
  481.         if(!any(is.na(stats))) {
  482.             wid <- wid/2
  483.             if(notch) {
  484.                 xx <- x+wid*c(-1,1,1,0.5,1,1,-1,-1,-0.5,-1)
  485.                 yy <- c(stats[c(2,2)],conf[1],stats[3],conf[2],
  486.                     stats[c(4,4)],conf[2],stats[3],conf[1])
  487.                 polygon(xx, yy, col=col, border=border)
  488.                 segments(x-wid/2, stats[3], x+wid/2, stats[3], col=border)
  489.             }
  490.             else {
  491.                 xx <- x+wid*c(-1,1,1,-1)
  492.                 yy <- stats[c(2,2,4,4)]
  493.                 polygon(xx, yy, col=col, border=border)
  494.                 segments(x-wid,stats[3],x+wid,stats[3],col=border)
  495.             }
  496.             segments(rep(x,2),stats[c(1,5)], rep(x,2), stats[c(2,4)], lty="dashed",col=border)
  497.             segments(rep(x-wid/2,2),stats[c(1,5)],rep(x+wid/2,2), stats[c(1,5)],col=border)
  498.             points(rep(x,length(out)), out, col=border)
  499.         }
  500.     }
  501.     n <- length(z)
  502.     limits <- numeric(0)
  503.     nmax <- 0
  504.     for(i in 1:n) {
  505.         nmax <- max(nmax,z[[i]]$n)
  506.         limits <- range(limits, z[[i]]$stats, z[[i]]$out)
  507.     }
  508.     if(!is.null(width)) {
  509.         if(length(width) != n | any(is.na(width)) | any(width <= 0))
  510.             stop("invalid boxplot widths")
  511.         width <- 0.8*width/max(width)
  512.     }
  513.     else if(varwidth) {
  514.         width <- 0.8*sqrt(z[[i]]$n/nmax)
  515.     }
  516.     if(n == 1) width <- 0.4
  517.     else width <- rep(0.8,n)
  518.     plot.new()
  519.     plot.window(xlim=c(0.5,n+0.5), ylim=limits, log=log)
  520.     for(i in 1:n) {
  521.         if(missing(border) || length(border)==0)
  522.             border <- par("fg")
  523.         bplt(i,width[i],z[[i]]$stats,z[[i]]$out,
  524.             z[[i]]$conf,notch=notch,
  525.             border=border[(i-1)%%length(border)+1],
  526.             col=if(is.null(col)) col
  527.             else col[(i-1)%%length(col)+1])
  528.     }
  529.     if(n > 1) axis(1, at=1:n, labels=names(z))
  530.     axis(2)
  531.     do.call("title", c(pars, list(...)))
  532.     box()
  533.     invisible(1:n)
  534. }
  535. builtins <- function(internal=FALSE)
  536. .Internal(builtins(internal))
  537. cbind <- function(...) {
  538.     if(any.data.frame(...))
  539.         data.frame(...)
  540.     else
  541.         .Internal(cbind(...))
  542. }
  543. cat <- function(...,file="",sep=" ", fill=FALSE, labels=NULL,append=FALSE)
  544.     .Internal(cat(list(...),file,sep,fill,labels,append))
  545. #nchar <- function(x) {
  546. #    x<-as.character(x)
  547. #    .Internal(nchar(x))
  548. #}
  549. substr <- function(x,start,stop) {
  550.     x<-as.character(x)
  551.     .Internal(substr(x,as.integer(start),as.integer(stop)))
  552. }
  553. strsplit <- function(x,split) {
  554.     x<-as.character(x)
  555.     split<-as.character(split)
  556.     .Internal(strsplit(x,split))
  557. }
  558. substring <- function(text,first,last=1000000)
  559. {
  560.         storage.mode(text) <- "character"
  561.         n <- max(length(text), length(first), length(last))
  562.         text <- rep(text, length = n)
  563.         first <- rep(first, length = n)
  564.         last <- rep(last, length = n)
  565.         substr(text, first, last)
  566. }
  567. abbreviate<-function(names.arg, minlength = 4, use.classes = T, dot = F)
  568. {
  569.         #we just ignore use.classes
  570.         if(minlength<=0)
  571.                 return(rep("",length(names.arg)))
  572.         names.arg<-as.character(names.arg)
  573.         dups<-duplicated(names.arg)
  574.         old<-names.arg
  575.         if(any(dups))
  576.                 names.arg<-names.arg[!dups]
  577.         dup2<-rep(T,length(names.arg))
  578.         x<-these<-names.arg
  579.         repeat {
  580.                 ans<-.Internal(abbreviate(these,minlength,use.classes))
  581.                 x[dup2]<-ans
  582.                 dup2<-duplicated(x)
  583.                 if(!any(dup2))
  584.                         break
  585.                 minlength<-minlength+1
  586.                 dup2 <- dup2 | match(x, x[duplicated(x)], 0)
  587.                 these<-names.arg[dup2]
  588.         }
  589.         if(any(dups))
  590.                 x<-x[match(old,names.arg)]
  591.         if(dot)
  592.                 x<-paste(x,".",sep="")
  593.         names(x)<-old
  594.         x
  595. }
  596. chisquare.test <- function (x, y=NULL, correct=TRUE,
  597.     p = rep(1/length(x), length(x)))
  598. {
  599.     if (is.matrix(x)) 
  600.         if ((nrow(x) == 1) || (ncol(x) == 1)) 
  601.             x <- as.vector(x)
  602.     if (!is.null(y) && !is.matrix(x))  {
  603.         x <- factor(x)
  604.         y <- factor(y)
  605.         x <- table(x,y)
  606.     }
  607.     if (is.matrix(x)) {
  608.         row.totals <- apply(x, 1, sum)
  609.         col.totals <- apply(x, 2, sum)
  610.         E <- outer(row.totals, col.totals, "*")/sum(x)
  611.         df <- (nrow(x) - 1) * (ncol(x) - 1)
  612.         if (correct && nrow(x) == 2 && ncol(x) == 2) 
  613.             yates <- .5 
  614.         else yates <- 0
  615.         chi <- (abs(x - E) - yates)^2/E
  616.         dimnames(E) <- dimnames(x)
  617.         dimnames(chi) <- dimnames(x)
  618.     }
  619.     else {
  620.         if (length(x) != length(p)) 
  621.             stop("Arguments must be same length")
  622.         E <- sum(x) * p
  623.         df <- length(x) - 1
  624.         chi <- (x - E)^2/E
  625.         names(chi) <- names(x)
  626.         names(E) <- names(x)
  627.     }
  628.     cat("X =", round(sum(chi), 4), " df =", df, "  p-value =",
  629.         round(1 - pchisq(sum(chi), df), 4), "\n")
  630.     invisible(list(E = E, chi = chi))
  631. }
  632. chol <- function(x)
  633. {
  634.     if(!is.numeric(x))
  635.         stop("non-numeric argument to chol")
  636.     if(is.matrix(x)) {
  637.         if(nrow(x) != ncol(x))
  638.             stop("non-square matrix in chol")
  639.         n <- nrow(x)
  640.     }
  641.     else {
  642.         if(length(x) != 1)
  643.             stop("non-matrix argument to chol")
  644.         n <- as.integer(1)
  645.     }
  646.     if(!is.double(x)) storage.mode(x) <- "double"
  647.     z <- .Fortran("chol",
  648.         x=x,
  649.         n,
  650.         n,
  651.         v=matrix(0, nr=n, nc=n),
  652.         info=integer(1),
  653.         DUP=FALSE)
  654.     if(z$info)
  655.         stop("singular matrix in chol")
  656.     z$v
  657. }
  658. chol2inv <- function(x, size=ncol(x))
  659. {
  660.     if(!is.numeric(x))
  661.         stop("non-numeric argument to chol2inv")
  662.     if(is.matrix(x)) {
  663.         nr <- nrow(x)
  664.         nc <- ncol(x)
  665.     }
  666.     else {
  667.         nr <- length(x)
  668.         nc <- as.integer(1)
  669.     }
  670.     size <- as.integer(size)
  671.     if(size <= 0 || size > nr || size > nc)
  672.         stop("invalid size argument in chol2inv")
  673.     if(!is.double(x)) storage.mode(x) <- "double"
  674.     z <- .Fortran("ch2inv",
  675.         x=x,
  676.         nr,
  677.         size,
  678.         v=matrix(0, nr=size, nc=size),
  679.         info=integer(1),
  680.         DUP=FALSE)
  681.     if(z$info)
  682.         stop("singular matrix in chol2inv")
  683.     z$v
  684. }
  685. colnames <- function(x) {
  686.     dn <- dimnames(x)
  687.     if(is.null(dn)) dn else dn[[2]]
  688. }
  689. "colnames<-" <- function(x, value) {
  690.     dn <- dimnames(x)
  691.     if(is.null(dn)) dimnames(x) <- list(dn, value)
  692.     else dimnames(x) <- list(dn[[1]], value)
  693.     x
  694. }
  695. rgb <- function(r, g, b, names=NULL)
  696. .Internal(rgb(r, g, b, names))
  697. hsv <- function(h=1,s=1,v=1,gamma=1)
  698. .Internal(hsv(h,s,v,gamma))
  699. # This is a quick little ``rainbow'' function.
  700. rainbow <-
  701. function (n, s=1, v=1, start=0, end=(n-1)/n, gamma=1)
  702. {
  703.     hsv(seq(start, end, length=n), s, v, gamma)
  704. }
  705. "topo.colors" <-
  706. function (n) 
  707. {
  708.     j <- round(n/3)
  709.     k <- round(n/3)
  710.     i <- n - j - k
  711.     rval <- rainbow(i, start = 43/60, end = 31/60)
  712.     rval <- c(rval, rainbow(j, start = 23/60, end = 10/60))
  713.     rval <- c(rval, hsv(seq(from = 10/60, to = 6/60, length.out = k),
  714.         s = seq(from = 1, to = 0.3, length.out = k), 1))
  715.     rval
  716. }
  717. "terrain.colors" <-
  718. function (n) 
  719. {
  720.     j <- round(n/3)
  721.     k <- round(n/3)
  722.     i <- n - j - k
  723.     rval <- hsv(23/60, 1, v = seq(0.6, 0.85, len = i))
  724.     rval <- c(rval, hsv(seq(23/60, 10/60, length = j), s = 1,
  725.         v = seq(0.85 , 1, length = j)))
  726.     rval <- c(rval, hsv(seq(from = 10/60, to = 6/60, length.out = k),
  727.         s = seq(from = 1 , to = 0.3, length.out = k), 1))
  728.     rval
  729. }
  730. "heat.colors" <-
  731. function (n) 
  732. {
  733.     j <- round(n/4)
  734.     i <- n - j
  735.     rval <- rainbow(i, start = 0, end = 1/6)
  736.     if (i>0) rval <- c(rval, hsv(1/6, seq(from = 1, to = 1/(2*j),
  737.             length.out = j), 1))
  738. }
  739. complete.cases <- function(...) .Internal(complete.cases(...))
  740. pi <- 4*atan(1)
  741. letters <- c(
  742. "a","b","c","d","e","f","g","h","i","j","k","l", "m",
  743. "n","o","p","q","r","s","t","u","v","w","x","y","z")
  744. LETTERS <- c(
  745. "A","B","C","D","E","F","G","H","I","J","K","L", "M",
  746. "N","O","P","Q","R","S","T","U","V","W","X","Y","Z")
  747. month.name <- c(
  748. "January", "February", "March", "April", "May", "June",
  749. "July", "August", "September", "October", "November", "December")
  750. month.abb <- c(
  751. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  752. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
  753. contour <- function(x=seq(0,1,len=nrow(z)), y=seq(0,1,len=ncol(z)), z,
  754.     nlevels=10, levels=pretty(range(z,na.rm=TRUE), nlevels), labcex=0,
  755.     col=par("fg"), lty=par("lty"), add=FALSE)
  756. {
  757.     if(is.list(x)) {
  758.         x <- x$x
  759.         y <- x$y
  760.     }
  761.     if(any(diff(x) <= 0) || any(diff(y) <= 0))
  762.         stop("increasing x and y values expected")
  763.     if(!add) {
  764.         plot.new()
  765.         plot.window(range(x), range(y), "")
  766.     }
  767.     .Internal(contour(x, y, z, levels, col=col, lty=lty))
  768.     if(!add) {
  769.         axis(1)
  770.         axis(2)
  771.         box()
  772.     }
  773.     invisible()
  774. }
  775. contrasts <-
  776. function(x, contrasts=TRUE)
  777. {
  778.     if (!is.factor(x))
  779.         stop("contrasts apply only to factors")
  780.     ctr <- attr(x,"contrasts")
  781.     if(is.null(ctr)) {
  782.         if(is.ordered(x))
  783.             ctr <- get(options("contrasts")[[1]][[2]])(levels(x), contrasts=contrasts)
  784.         else
  785.             ctr <- get(options("contrasts")[[1]][[1]])(levels(x), contrasts=contrasts)
  786.         dimnames(ctr) <- list(levels(x), dimnames(ctr)[[2]])
  787.     }
  788.     else if(is.character(ctr))
  789.         ctr <- get(ctr)(levels(x), contrasts=contrasts)
  790.     ctr
  791. }
  792. "contrasts<-" <-
  793. function(x, ctr)
  794. {
  795.     if(!is.factor(x))
  796.         stop("contrasts apply only to factors")
  797.     if(is.numeric(ctr)) {
  798.         ctr <- as.matrix(ctr)
  799.         nlevs <- nlevels(x)
  800.         if(nrow(ctr) != nlevs || ncol(ctr) >= nlevs)
  801.             stop("invalid contrast matrix extents")
  802.         cm <- qr(cbind(1,ctr))
  803.         if(cm$rank != ncol(ctr)+1) stop("singular contrast matrix")
  804.         cm <- qr.qy(cm, diag(nlevs))[,2:nlevs]
  805.         cm[,1:ncol(ctr)] <- ctr
  806.         dimnames(cm) <- list(levels(x),NULL)
  807.     }
  808.     else if(is.character(ctr))
  809.         cm <- ctr
  810.     else if(is.null(ctr))
  811.         cm <- NULL
  812.     else stop("numeric contrasts or contrast name expected")
  813.     attr(x, "contrasts") <- cm
  814.     x
  815. }
  816. contr.poly <-
  817. function(n, contrasts=TRUE)
  818. {
  819.     normalize <- function(x) x/sqrt(sum(x^2))
  820.     if(is.numeric(n) && length(n) == 1)
  821.         levs <- 1:n
  822.     else {
  823.         levs <- n
  824.         n <- length(n)
  825.     }
  826.     if(n < 2)
  827.         stop(paste("Contrasts not defined for", n - 1,
  828.             "degrees of freedom"))
  829.     contr <- matrix(0, n, n)
  830.     x <- 1:n
  831.     d <- x - mean(x)
  832.     contr[,1] <- rep(1/sqrt(n),n)
  833.     contr[,2] <- normalize(d)
  834.     if(n > 2)
  835.         for(i in 3:n) {
  836.             a1 <- sum(d*contr[,i-1]*contr[,i-1])
  837.             a2 <- sum(d*contr[,i-1]*contr[,i-2])
  838.             contr[,i] <- normalize((d-a1)*contr[,i-1]-a2*contr[,i-2])
  839.         }
  840.     dimnames(contr) <- list(levs, paste("^", 0:(n-1), sep=""))
  841.     if(contrasts) {
  842.         contr[, -1, drop=FALSE]
  843.     }
  844.     else {
  845.         contr[, 1] <- 1
  846.         contr
  847.     }
  848. }
  849. contr.helmert <-
  850. function (n, contrasts=TRUE) 
  851. {
  852.     if (length(n) <= 1) {
  853.         if(is.numeric(n) && length(n) == 1 && n > 1) levels <- 1:n
  854.         else stop("contrasts are not defined for 0 degrees of freedom")
  855.     }
  856.     else levels <- n
  857.     lenglev <- length(levels)
  858.     if (contrasts) {
  859.         cont <- array(-1, c(lenglev, lenglev-1), list(levels, NULL))
  860.         cont[col(cont) <= row(cont) - 2] <- 0
  861.         cont[col(cont) == row(cont) - 1] <- 1:(lenglev-1)
  862.     }
  863.     else {
  864.         cont <- array(0, c(lenglev, lenglev), list(levels, levels))
  865.         cont[col(cont) == row(cont)] <- 1
  866.     }
  867.     cont
  868. }
  869. contr.treatment <-
  870. function(n, contrasts = TRUE)
  871. {
  872.     if(is.numeric(n) && length(n) == 1)
  873.         levs <- 1:n
  874.     else {
  875.         levs <- n
  876.         n <- length(n)
  877.     }
  878.     contr <- array(0, c(n, n), list(levs, levs))
  879.     contr[seq(1, n^2, n + 1)] <- 1
  880.     if(contrasts) { 
  881.         if(n < 2)
  882.             stop(paste("Contrasts not defined for", n - 1,
  883.                 "degrees of freedom"))
  884.         contr <- contr[, -1, drop = FALSE]
  885.     }
  886.     contr
  887. }
  888. contr.sum <-
  889. function (n, contrasts=TRUE) 
  890. {
  891.     if (length(n) <= 1) {
  892.         if (is.numeric(n) && length(n) == 1 && n > 1) 
  893.             levels <- 1:n
  894.         else stop("Not enough degrees of freedom to define contrasts")
  895.     }
  896.     else levels <- n
  897.     lenglev <- length(levels)
  898.     if (contrasts) {
  899.         cont <- array(0, c(lenglev, lenglev - 1), list(levels, NULL))
  900.         cont[col(cont) == row(cont)] <- 1
  901.         cont[lenglev, ] <- -1
  902.     }
  903.     else {
  904.         cont <- array(0, c(lenglev, lenglev), list(levels, levels))
  905.         cont[col(cont) == row(cont)] <- 1
  906.     }
  907.     cont
  908. }
  909. "co.intervals" <-
  910. function (x, number = 6, overlap = 0.5) 
  911. {
  912.         x <- sort(x[!is.na(x)])
  913.         n <- length(x)
  914.         # "from the record"
  915.         r <- n/(number * (1 - overlap) + overlap)
  916.         l <- round(1 + 0:(number - 1) * (1 - overlap) * r)
  917.         u <- round(r + 0:(number - 1) * (1 - overlap) * r)
  918.         cbind(x[l], x[u])
  919. }
  920. panel.smooth <-
  921. function(x, y, col, pch, f=2/3, iter=3, ...)
  922. {
  923.     points(x, y, pch=pch, col=col)
  924.     lines(lowess(x, y, f=f, iter=iter), ...)
  925. }
  926. "coplot" <-
  927. function (formula, data, given.values, panel=points, rows, columns, show.given = TRUE,
  928.     col = par("fg"), pch=par("pch"), ...)
  929. {
  930.     deparen <- function(expr) {
  931.         while (is.language(expr) && !is.name(expr) && deparse(expr[[1]]) == "(") expr <- expr[[2]]
  932.         expr
  933.     }
  934.     bad.formula <- function() stop("invalid conditioning formula")
  935.     bad.lengths <- function() stop("incompatible variable lengths")
  936.     #  parse and check the formula
  937.     formula <- deparen(formula)
  938.     if (deparse(formula[[1]]) != "~")
  939.         bad.formula()
  940.     y <- deparen(formula[[2]])
  941.     rhs <- deparen(formula[[3]])
  942.     if (deparse(rhs[[1]]) != "|")
  943.         bad.formula()
  944.     x <- deparen(rhs[[2]])
  945.     rhs <- deparen(rhs[[3]])
  946.     if (is.language(rhs) && !is.name(rhs)
  947.         && (deparse(rhs[[1]]) == "*" || deparse(rhs[[1]]) == "+")) {
  948.         have.b <- TRUE
  949.         a <- deparen(rhs[[2]])
  950.         b <- deparen(rhs[[3]])
  951.     }
  952.     else {
  953.         have.b <- FALSE
  954.         a <- rhs
  955.     }
  956.     #  evaluate the formulae components to get the data values
  957.     if (missing(data)) 
  958.         data <- sys.frame(sys.parent())
  959.     x.name <- deparse(x)
  960.     x <- eval(x, data)
  961.     nobs <- length(x)
  962.     y.name <- deparse(y)
  963.     y <- eval(y, data)
  964.     if(length(y) != nobs) bad.lengths()
  965.     a.name <- deparse(a)
  966.     a <- eval(a, data)
  967.     if(length(a) != nobs) bad.lengths()
  968.     if (have.b) {
  969.         b.name <- deparse(b)
  970.         b <- eval(b, data)
  971.         if(length(b) != nobs) bad.lengths()
  972.     }
  973.     else b <- NULL
  974.     #  generate the given value intervals
  975.     bad.givens <- function() stop("invalid given.values")
  976.     if(missing(given.values)) {
  977.         if(is.factor(a)) {
  978.             a.intervals <- cbind(1:nlevels(a), 1:nlevels(a))
  979.             a <- codes(a)
  980.         }
  981.         else a.intervals <- co.intervals(a)
  982.         b.intervals <- NULL
  983.         if (have.b)  {
  984.             if(is.factor(b)) {
  985.                 b.intervals <- cbind(1:nlevels(b), 1:nlevels(b))
  986.                 b <- codes(b)
  987.             }
  988.             else b.intervals <- co.intervals(b)
  989.         }
  990.     }
  991.     else {
  992.         if(!is.list(given.values))
  993.             given.values <- list(given.values)
  994.         if(length(given.values) != (if(have.b) 2 else 1))
  995.             bad.givens()
  996.         a.intervals <- given.values[[1]]
  997.         if(is.factor(a)) {
  998.             if(is.character(a.intervals))
  999.                 a.levels <- match(a.levels, levels(a))
  1000.             else a.levels <- cbind(a.levels, a.levels)
  1001.             a <- codes(a)
  1002.         }
  1003.         else if(is.numeric(a)) {
  1004.             if(!is.numeric(a)) bad.givens()
  1005.             if(!is.matrix(a.intervals) || ncol(a.intervals) != 2)
  1006.                 a.intervals <- cbind(a.intervals, a.intervals)
  1007.         }
  1008.         if(have.b) {
  1009.             b.intervals <- given.values[[2]]
  1010.             if(is.factor(b)) {
  1011.                 if(is.character(b.intervals))
  1012.                     b.levels <- match(b.levels, levels(b))
  1013.                 else b.levels <- cbind(b.levels, b.levels)
  1014.                 b <- codes(b)
  1015.             }
  1016.             else if(is.numeric(b)) {
  1017.                 if(!is.numeric(b)) bad.givens()
  1018.                 if(!is.matrix(b.intervals) || ncol(b.intervals) != 2)
  1019.                     b.intervals <- cbind(b.intervals, b.intervals)
  1020.             }
  1021.         }
  1022.     }
  1023.     if(any(is.na(a.intervals))) bad.givens()
  1024.     if(have.b)
  1025.         if(any(is.na(b.intervals))) bad.givens()
  1026.     #  compute the page layout
  1027.     if (have.b) {
  1028.         rows <- nrow(b.intervals)
  1029.         columns <- nrow(b.intervals)
  1030.         nplots <- rows * columns
  1031.         total.rows <- rows + if (show.given) 
  1032.             1
  1033.         else 0
  1034.         total.columns <- columns + if (show.given) 
  1035.             1
  1036.         else 0
  1037.     }
  1038.     else {
  1039.         nplots <- nrow(a.intervals)
  1040.         if (missing(rows)) {
  1041.             if (missing(columns)) {
  1042.                 rows <- ceiling(round(sqrt(nplots)))
  1043.                 columns <- ceiling(nplots/rows)
  1044.             }
  1045.             else rows <- ceiling(nplots/columns)
  1046.         }
  1047.         else if (missing(columns)) 
  1048.             columns <- ceiling(nplots/rows)
  1049.         if (rows * columns < nplots) 
  1050.             stop("rows * columns too small")
  1051.         total.rows <- rows + if (show.given) 
  1052.             1
  1053.         else 0
  1054.         total.columns <- columns
  1055.     }
  1056.     #  plot that sucker!
  1057.     if(have.b) oma <- rep(5, 4) else oma <- c(5, 6, 5, 4)
  1058.     opar <- par(mfrow = c(total.rows, total.columns),
  1059.             oma = oma,
  1060.             mar = if (have.b) rep(0, 4) else c(0.5, 0, 0.5, 0),
  1061.             new = FALSE)
  1062.     on.exit(par(opar))
  1063.     plot.new()
  1064.     xlim <- range(x, na.rm = TRUE)
  1065.     ylim <- range(y, na.rm = TRUE)
  1066.     pch <- rep(pch, length=nobs)
  1067.     col <- rep(col, length=nobs)
  1068.     do.panel <- function(index) {
  1069.         istart <- (total.rows - rows) + 1
  1070.         i <- total.rows - ((index - 1)%/%columns)
  1071.         j <- (index - 1)%%columns + 1
  1072.         par(mfg = c(i, j, total.rows, total.columns), new = TRUE)
  1073.         plot.new()
  1074.         plot.window(xlim, ylim, log = "")
  1075.         if(any(id)) {
  1076.             grid(lty="solid")
  1077.             panel(x[id], y[id], col = col[id], pch=pch[id], ...)
  1078.         }
  1079.         if ((i == total.rows) && (j%%2 == 0))
  1080.             axis(1)
  1081.         if ((i == istart || index + columns > nplots) && (j%%2 == 1))
  1082.             axis(3)
  1083.         if ((j == 1) && ((total.rows - i)%%2 == 0))
  1084.             axis(2)
  1085.         if ((j == columns || index == nplots) && ((total.rows - i)%%2 == 1))
  1086.             axis(4)
  1087. #        if (i == total.rows)
  1088. #            axis(1, labels = (j%%2 == 0))
  1089. #        if (i == istart || index + columns > nplots) 
  1090. #            axis(3, labels = (j%%2 == 1))
  1091. #        if (j == 1) 
  1092. #            axis(2, labels = ((total.rows - i)%%2 == 0))
  1093. #        if (j == columns || index == nplots) 
  1094. #            axis(4, labels = ((total.rows - i)%%2 == 1))
  1095.         box()
  1096.     }
  1097.     if(have.b) {
  1098.         count <- 1
  1099.         for(i in 1:rows) {
  1100.             for(j in 1:columns) {
  1101.                 id <- ((a.intervals[j,1] <= a)
  1102.                     & (a <= a.intervals[j,2])
  1103.                     & (b.intervals[i,1] <= b)
  1104.                     & (b <= b.intervals[i,2]))
  1105.                 do.panel(count)
  1106.                 count <- count + 1
  1107.             }
  1108.         }
  1109.     }
  1110.     else {
  1111.         for (i in 1:nplots) {
  1112.             id <- ((a.intervals[i,1] <= a)
  1113.                 & (a <= a.intervals[i,2]))
  1114.             do.panel(i)
  1115.         }
  1116.     }
  1117.     mtext(x.name, side=1, at=0.5*(columns/total.columns),
  1118.         outer=TRUE, line=5, xpd=TRUE)
  1119.     mtext(y.name, side=2, at=0.5*(rows/total.rows),
  1120.         outer=TRUE, line=4, xpd=TRUE)
  1121.     if(show.given) {
  1122.         mar <- par("mar")
  1123.         nmar <- mar + c(4,0,0,0)
  1124.         par(fig = c(0, columns/total.columns, rows/total.rows, 1),
  1125.             mar=nmar, new=TRUE)
  1126.         plot.new()
  1127.         nint <- nrow(a.intervals)
  1128.         plot.window(range(a.intervals, na.rm=T),
  1129.             c(0.5, nint+0.5), log="")
  1130.         rect(a.intervals[,1], 1:nint-0.3,
  1131.             a.intervals[,2], 1:nint+0.3, col=gray(0.9))
  1132.         axis(3)
  1133.         axis(1, labels=FALSE)
  1134.         box()
  1135.         mtext(paste("Given :", a.name),
  1136.             side=3, at=mean(par("usr")[1:2]), line=3, xpd=T)
  1137.         if(have.b) {
  1138.                 nmar <- mar + c(0, 4, 0, 0)
  1139.             par(fig = c(columns/total.columns, 1,
  1140.                 0, rows/total.rows), mar=nmar, new=TRUE)
  1141.             plot.new()
  1142.             nint <- nrow(b.intervals)
  1143.             plot.window(c(0.5, nint+0.5),
  1144.                 range(b.intervals, na.rm=T), log="")
  1145.             rect(1:nint-0.3, b.intervals[,1],
  1146.                 1:nint+0.3, b.intervals[,2], col=gray(0.9))
  1147.             axis(4)
  1148.             axis(2, labels=FALSE)
  1149.             box()
  1150.             mtext(paste("Given :", b.name),
  1151.                 side=4, at=mean(par("usr")[3:4]), line=3, xpd=T)
  1152.         }
  1153.     }
  1154. }
  1155. cor <- function (x, y=NULL, use="all.obs")
  1156. {
  1157.     na.method <- pmatch(use, c("all.obs", "complete.obs", "pairwise.complete.obs"))
  1158.     .Internal(cor(as.matrix(x), if(is.null(y)) y else as.matrix(y), na.method))
  1159. }
  1160. cov <- function (x, y=NULL, use="all.obs") 
  1161. {
  1162.     na.method <- pmatch(use, c("all.obs", "complete.obs", "pairwise.complete.obs"))
  1163.     .Internal(cov(as.matrix(x), if(is.null(y)) y else as.matrix(y), na.method))
  1164. }
  1165. curve <- function(expr, from, to, n=100, add=FALSE, type="l", ...) {
  1166.     expr <- substitute(expr)
  1167.     lims <- par("usr")
  1168.     if(missing(from)) from <- lims[1]
  1169.     if(missing(to)) to <- lims[2]
  1170.     x <- seq(from,to,length=n)
  1171.     y <- eval(expr)
  1172.     if(add)
  1173.         lines(x, y, ...)
  1174.     else
  1175.         plot(x, y, type="l", ...)
  1176. }
  1177. cut <- function(x, breaks, labels) {
  1178.     if (!is.numeric(x))
  1179.         stop("cut: x must be numeric")
  1180.     if (length(breaks) == 1) {
  1181.         if (is.na(breaks) | breaks < 2)
  1182.             stop("invalid number of breaks")
  1183.         nbreaks <- breaks
  1184.         breaks <- range(x,na.rm=TRUE)
  1185.         #breaks <- pretty(breaks + c(0, diff(breaks)/1000), nbreaks)
  1186.         breaks <- seq(breaks[1]-diff(breaks)/1000,breaks[2]+diff(breaks)/1000, len=nbreaks+1)
  1187.     }
  1188.     breaks <- sort(breaks)
  1189.     if(any(duplicated(breaks)))
  1190.         stop("cut: breaks are not unique")
  1191.     if(missing(labels)) {
  1192.         labels <- paste("Range",1:(length(breaks)-1))
  1193.     }
  1194.     else {
  1195.         if(length(labels)!=length(breaks)-1)
  1196.             stop("labels/breaks length conflict")
  1197.     }
  1198.     codes <- .C("bincode",
  1199.         as.double(x),
  1200.         length(x),
  1201.         as.double(breaks),
  1202.         length(breaks),
  1203.         integer(length(x)),
  1204.         TRUE)[[5]]
  1205.     factor(codes,1:max(codes),labels)
  1206. }
  1207. data <- function(..., list=character(0))
  1208. {
  1209.     names <- c(as.character(substitute(list(...))[-1]), list)
  1210.     if(length(names) == 0) {
  1211.         system(paste("$RHOME/cmd/pager", system.file("data",
  1212.             "index.doc")))
  1213.     }
  1214.     else
  1215.         for(name in names) {
  1216.             file <- system.file("data", name)
  1217.             if(file == "") stop(paste("no data set called", name))
  1218.             else source(file)
  1219.     }
  1220.     invisible(names)
  1221. }
  1222. data.matrix <-
  1223. function(frame)
  1224. {
  1225.     if(!is.data.frame(frame))
  1226.         return(as.matrix(frame))
  1227.     log <- unlist(lapply(frame, is.logical))
  1228.     num <- unlist(lapply(frame, is.numeric))
  1229.     fac <- unlist(lapply(frame, is.factor))
  1230.     if(!all(log|fac|num))
  1231.         stop("non-numeric data type in frame")
  1232.     d <- dim(frame)
  1233.     x <- matrix(nr=d[1],nc=d[2],dimnames=dimnames(frame))
  1234.     for(i in 1:length(frame)) {
  1235.         xi <- frame[[i]]
  1236.         if(is.logical(xi)) x[,i] <- as.numeric(xi)
  1237.         else if(is.numeric(xi)) x[,i] <- xi
  1238.         else x[,i] <- codes(xi)
  1239.     }
  1240.     x
  1241. }
  1242. frame.cvt <-
  1243. function(x, as.is=FALSE)
  1244. {
  1245.     if(!as.is && (is.character(x) || is.logical(x)))
  1246.         x <- factor(x)
  1247.     x
  1248. }
  1249. data.frame <- 
  1250. function (..., row.names=NULL, col.names=NULL, as.is=FALSE)
  1251. {
  1252.     frame <- list(...)
  1253.     n <- length(frame)
  1254.     as.is <- rep(as.is, length=n)
  1255.     for(i in 1:n) {
  1256.         as.is.i <- attr(frame[[i]], "AsIs")
  1257.         if(!is.null(as.is.i))
  1258.             as.is[i] <- as.is.i
  1259.     }
  1260.     if (is.null(col.names)) {
  1261.         v <- substitute(list(...))[-1]
  1262.         for (i in 1:length(v)) if (!is.symbol(v[[i]])) 
  1263.             v[[i]] <- paste("X", i, sep="")
  1264.         arg.names <- as.character(v)
  1265.         col.names <- names(frame)
  1266.         if (is.null(col.names)) 
  1267.             col.names <- arg.names
  1268.         else {
  1269.             nameless <- (nchar(col.names) == 0)
  1270.             col.names[nameless] <- arg.names[nameless]
  1271.         }
  1272.     }
  1273.     names(frame) <- as.character(col.names)
  1274.     for (i in 1:length(frame)) {
  1275.         if (is.list(frame[[i]])) 
  1276.             for (j in 1:length(frame[[i]])){
  1277.                 if (!is.numeric(frame[[i]][[j]]) && !is.factor(frame[[i]][[j]]))
  1278.                     frame[[i]][[j]] <- frame.cvt(frame[[i]][[j]], as.is=as.is[i])
  1279.         }
  1280.         else {
  1281.             if (!is.numeric(frame[[i]]) && !is.factor(frame[[i]]))
  1282.                 frame[[i]] <- frame.cvt(frame[[i]], as.is=as.is[i])
  1283.         }
  1284.     }
  1285.     .Internal(data.frame(frame, as.character(row.names), as.logical(as.is)))
  1286. }
  1287. row.names <- function(x) attr(x,"row.names")
  1288. "row.names<-" <- function(x,value) {
  1289.     if( !is.data.frame(x) )
  1290.         return(data.frame(x, row.names=value))
  1291.     else
  1292.         attr(x,"row.names") <- as.character(value)
  1293.     x
  1294. }
  1295. "is.na.data.frame" <-
  1296. function (x) 
  1297. {
  1298.         y <- do.call("cbind", lapply(x, "is.na"))
  1299.         rownames(y) <- row.names(x)
  1300.         y
  1301. }
  1302. I <- function(x) {
  1303.     attr(x,"AsIs") <- TRUE
  1304.     x
  1305. }
  1306. plot.data.frame <- 
  1307. function (x, ...) 
  1308. {
  1309.     if (!is.data.frame(x)) 
  1310.         stop("plot.data.frame applied to non data frame")
  1311.     xm <- data.matrix(x)
  1312.     if (ncol(xm) == 1) {
  1313.         stripplot(x, ...)
  1314.     }
  1315.     else if (ncol(xm) == 2) {
  1316.         plot(xm)
  1317.     }
  1318.     else {
  1319.         pairs(xm, ...)
  1320.     }
  1321. }
  1322. t.data.frame<- function(x)
  1323. {
  1324.     x <- as.matrix(x)
  1325.     NextMethod("t")
  1326. }   
  1327. de.ncols <- function(inlist)
  1328. {
  1329.     ncols <- matrix(0, nrow=length(inlist), ncol=2)
  1330.     i <- 1
  1331.     for( telt in inlist ) {
  1332.         if( is.matrix(telt) ) {
  1333.                 ncols[i, 1] <- ncol(telt)
  1334.                 ncols[i, 2] <- 2
  1335.         }
  1336.         else if( is.list(telt) ) {
  1337.             for( telt2 in telt )
  1338.                 if( !is.vector(telt2) ) stop("wrong argument to dataentry")
  1339.             ncols[i, 1] <- length(telt)
  1340.             ncols[i, 2] <- 3
  1341.         }
  1342.         else if( is.vector(telt) ) {
  1343.             ncols[i, 1] <- 1
  1344.             ncols[i, 2] <- 1
  1345.         }
  1346.         else stop("wrong argument to dataentry")
  1347.         i <- i+1
  1348.     }
  1349.     return(ncols)
  1350. }
  1351. de.setup <- function(ilist, list.names, incols)
  1352. {
  1353.     ilen <- sum(incols)
  1354.     ivec <- vector("list", ilen)
  1355.     inames <- vector("list", ilen)
  1356.     i <- 1
  1357.     k <- 0
  1358.     for( telt in ilist ) {
  1359.         k <- k+1
  1360.         if( is.list(telt) ) {
  1361.             y <- names(telt)
  1362.             for( j in 1:length(telt) ) {
  1363.                 ivec[[i]] <- telt[[j]]
  1364.                 if( is.null(y) || y[j]=="" )
  1365.                     inames[[i]] <- paste("var", i, sep="")
  1366.                 else inames[[i]] <- y[j]
  1367.                 i <- i+1
  1368.             }
  1369.         }
  1370.         else if( is.vector(telt) ) {
  1371.             ivec[[i]] <- telt
  1372.             inames[[i]] <- list.names[[k]]
  1373.             i <- i+1
  1374.         }
  1375.         else if( is.matrix(telt) ) {
  1376.             y <- dimnames(telt)[[2]]
  1377.             for( j in 1:ncol(telt) ) {
  1378.                 ivec[[i]] <- telt[, j]
  1379.                 if( is.null(y) || y[j]=="" )
  1380.                     inames[[i]] <- paste("var", i, sep="")
  1381.                 else inames[[i]] <- y[j]
  1382.                 i <- i+1
  1383.             }
  1384.         }
  1385.         else stop("wrong argument to dataentry")
  1386.     }
  1387.     names(ivec) <- inames
  1388.     return(ivec)
  1389. }
  1390. # take the data in inlist and restore it to the format described by ncols and coltypes
  1391. de.restore <- function(inlist, ncols, coltypes, argnames, args)
  1392. {
  1393.     rlist <- vector("list", length=length(ncols))
  1394.     rnames <- vector("character", length=length(ncols))
  1395.     j <- 1
  1396.     lnames <- names(inlist)
  1397.     for( i in 1:length(ncols) ) {
  1398.         if(coltypes[i]==2) {
  1399.             tlen <- length(inlist[[j]])
  1400.             x <- matrix(0, nrow=tlen, ncol=ncols[i])
  1401.             cnames <- vector("character", ncol(x))
  1402.             for( ind1 in 1:ncols[i]) {
  1403.                 if(tlen != length(inlist[[j]]) ) {
  1404.                     warning("could not restore type information")
  1405.                     return(inlist)
  1406.                 }
  1407.                 x[, ind1] <- inlist[[j]]
  1408.                 cnames[ind1] <- lnames[j]
  1409.                 j <- j+1
  1410.             }
  1411.             if( dim(x) == dim(args[[i]]) )
  1412.                 rn <- dimnames(args[[i]])[[1]]
  1413.             else rn <- NULL
  1414.             if( any(cnames!="") )
  1415.                 dimnames(x) <- list(rn, cnames)
  1416.             rlist[[i]] <- x
  1417.             rnames[i] <- argnames[i]
  1418.         }
  1419.         else if(coltypes[i]==3) {
  1420.             x <- vector("list", length=ncols[i])
  1421.             cnames <- vector("character", ncols[i])
  1422.             for( ind1 in 1:ncols[i]) {
  1423.                 x[[ind1]] <- inlist[[j]]
  1424.                 cnames[ind1] <- lnames[j]
  1425.                 j <- j+1
  1426.             }
  1427.             if( any(cnames!="") )
  1428.                 names(x) <- cnames
  1429.             rlist[[i]] <- x
  1430.             rnames[i] <- argnames[i]
  1431.         }
  1432.         else {
  1433.             rlist[[i]] <- inlist[[j]]
  1434.             j <- j+1
  1435.             rnames[i] <- argnames[i]
  1436.         }
  1437.     }
  1438.     names(rlist) <- rnames
  1439.     return(rlist)
  1440. }
  1441. de <- function(..., Modes=NULL, Names=NULL)
  1442. {
  1443.     sdata <- list(...)
  1444.     snames <- as.character(substitute(list(...))[-1])
  1445.     if( is.null(sdata) ) {
  1446.         if( is.null(Names) ) {
  1447.             if( !is.null(Modes) ) {
  1448.                 odata <- vector("list", length=length(Modes))
  1449.             }
  1450.             else odata <- vector("list", length=1)
  1451.         }
  1452.         else {
  1453.             if( (length(Names) != length(Modes)) && !is.null(Modes) ) {
  1454.                 warning("modes argument ignored")
  1455.                 Modes <- NULL
  1456.             }
  1457.             odata <- vector("list", length=length(Names))
  1458.             names(odata) <- Names
  1459.         }
  1460.         ncols <- rep(1, length(odata))
  1461.         coltypes <- rep(1, length(odata))
  1462.     }
  1463.     else {
  1464.         ncols <- de.ncols(sdata)
  1465.         coltypes <- ncols[, 2]
  1466.         ncols <- ncols[, 1]
  1467.         odata <- de.setup(sdata, snames, ncols)
  1468.         if( !is.null(Names) ) 
  1469.             if( length(Names) != length(odata) )
  1470.                 warning("names argument ignored")
  1471.             else names(odata) <- Names
  1472.         if( !is.null(Modes) )
  1473.             if( length(Modes) != length(odata) ) {
  1474.                 warning("modes argument ignored")
  1475.                 Modes <- NULL
  1476.             }
  1477.     }
  1478.     rdata <- dataentry(odata, Modes)
  1479.     t1 <- length(rdata)==sum(ncols)
  1480.     if( t1 && any(coltypes!=1) )
  1481.         rdata <- de.restore(rdata, ncols, coltypes, snames, sdata)
  1482.     else if( any(coltypes!=1) ) warning("could not restore data types properly")
  1483.     return(rdata)
  1484. }
  1485. data.entry <- function(..., Modes=NULL, Names=NULL)
  1486. {
  1487.     tmp1 <- de(..., Modes=Modes, Names=Names)
  1488.     j <- 1
  1489.     for(i in names(tmp1) ) {
  1490.         assign(i, tmp1[[j]], env=.GlobalEnv)
  1491.         j <- j+1
  1492.     }
  1493.     invisible(NULL)
  1494. }
  1495. "density" <-
  1496. function (x, bw, adjust=1, kernel="gaussian", n=512, width, from,
  1497.     to, cut = 3, plot.graph = FALSE)
  1498. {
  1499.     if (!is.numeric(x))
  1500.         stop("argument must be numeric")
  1501.     name <- deparse(substitute(x))
  1502.     x <- x[!is.na(x)]
  1503.         k.list <- c("gaussian", "rectangular", "triangular", "cosine")
  1504.         method <- pmatch(kernel, k.list)
  1505.         if(is.na(method))
  1506.           stop(paste("kernel must be a 'pmatch' of",
  1507.                      paste(k.list,collapse=', ')))
  1508.         if(n > 512) n <- 2^ceiling(log2(n)) #- to be fast with FFT
  1509.         if (missing(bw)) {
  1510.       if(missing(width))
  1511.         bw <- adjust * 1.06 * min(sd(x), IQR(x)/1.34) * length(x)^-0.2
  1512.       else
  1513.         bw <- 0.25 * width
  1514.         }
  1515.     if (missing(from))
  1516.         from <- min(x) - cut * bw
  1517.     if (missing(to))
  1518.         to <- max(x) + cut * bw
  1519.     y <- .C("massdist",
  1520.                 x = as.double(x),
  1521.                 nx= length(x),
  1522.                 xlo = as.double(from),
  1523.                 xhi = as.double(to),
  1524.                 y = double(2 * n),
  1525.                 ny= as.integer(n)) $ y
  1526.     xords <- seq(from, by = (to - from)/(n - 1), length = 2 * n)
  1527.     kords <- xords - from
  1528.     kords[(n + 2):(2 * n)] <- -kords[n:2]
  1529.     if (method == 1) {
  1530.         bw <- bw
  1531.         kords <- dnorm(kords, sd = bw)
  1532.     }
  1533.     else if (method == 2) {
  1534.         a <- bw/0.2886751
  1535.         kords <- ifelse(abs(kords) < 0.5 * a, 1/a, 0)
  1536.     }
  1537.     else if (method == 3) {
  1538.         a <- bw/0.4082483
  1539.         kords <- ifelse(abs(kords) < a, (1 - abs(kords)/a)/a, 0)
  1540.     }
  1541.     else if (method == 4) {
  1542.         a <- bw/1.135724
  1543.         kords <- ifelse(abs(kords) < a * pi, (1 + cos(kords/a))/(2*pi*a), 0)
  1544.     }
  1545.     else stop("unknown density estimation kernel")
  1546.     kords <- convolve(y, kords)[1:n]
  1547.     xords <- seq(from, by = (to - from)/(n - 1), length = n)
  1548.     structure(list(x = xords, y = kords, bw = bw,
  1549.         call=match.call(), name=name),
  1550.         class="density")
  1551. }
  1552. plot.density <-
  1553. function(s, main="", xlab, ylab="Density", type="l", ...)
  1554. {
  1555.     if(missing(xlab)) xlab <- paste("Bandwidth =", s$bw)
  1556.     plot.default(s, main=main, xlab=xlab, ylab=ylab, type=type, ...)
  1557. }
  1558. bw.ucv <-
  1559. function(x, samples=100)
  1560. {
  1561.         fucv <- function(h)   
  1562.                 .C("ucv", length(x), x,  as.double(h), u=1)$u                   
  1563.         n <- length(x)
  1564.         if(samples > 0 && n > samples) x <- sample(x, samples)
  1565.         hmax <- 1.144 * sqrt(var(x)) * length(x)^(-1/5) * 4
  1566.         storage.mode(x) <- "double"
  1567.         0.25 * optimize(fucv, c(0.1*hmax, hmax), tol=0.01*hmax)$minimum * (length(x)/n)^0.2
  1568. }
  1569. bw.bcv <- function(x, samples=100)
  1570. {
  1571.     fbcv <- function(h)
  1572.         .C("bcv", length(x), x,  as.double(h), u=1)$u
  1573.     n <- length(x)
  1574.     if(samples > 0 && n > samples) x <- sample(x, samples)
  1575.     hmax <- 1.144 * sqrt(var(x)) * length(x)^(-1/5) * 4
  1576.     storage.mode(x) <- "double"
  1577.     0.25 * optimize(fbcv, c(0.1*hmax, hmax), tol=0.01*hmax)$minimum * (length(x)/n)^0.2
  1578. }
  1579. bw.sj <- function(x, samples=100)
  1580. {
  1581.     SDh <- function(x, h) .C("phi4", length(x), x,  as.double(h), u=double(1))$u
  1582.     TDh <- function(x, h) .C("phi6", length(x), x, as.double(h), u=double(1))$u
  1583.     fSD <- function(h, x, alph2, c1) (c1/SDh(x, alph2 * h^(5/7)))^(1/5) - h
  1584.     lambda <- IQR(x)
  1585.     n1 <- length(x)
  1586.     if(samples > 0 && n1 > samples) x <- sample(x, samples)
  1587.     storage.mode(x) <- "double"
  1588.     n <- length(x)
  1589.     hmax <- 1.144 * sqrt(var(x)) * n^(-1/5)
  1590.     a <- 0.92 * lambda * n^(-1/7)
  1591.     b <- 0.912 * lambda * n^(-1/9)
  1592.     c1 <- 1/(2*sqrt(pi)*n)
  1593.     TD  <- -TDh(x, b)
  1594.     alph2 <- 1.357*(SDh(x,a)/TD)^(1/7)
  1595.     res <- uniroot(fSD, c(0.1*hmax, hmax), tol=0.01*hmax,
  1596.         x=x, alph2=alph2, c1=c1)$root
  1597.     res * (n/n1)^0.2
  1598. }
  1599. diag <-
  1600. function(x = 1, nrow, ncol = n)
  1601. {
  1602.     if(is.matrix(x) && nargs() == 1)
  1603.         return(as.matrix(x)[1 + 0:(min(dim(x)) - 1) * (dim(x)[1] + 1)])
  1604.     if(missing(x))
  1605.         n <- nrow
  1606.     else if(length(x) == 1 && missing(nrow) && missing(ncol)) {
  1607.         n <- as.integer(x)
  1608.         x <- 1
  1609.     }
  1610.     else n <- length(x)
  1611.     if(!missing(nrow))
  1612.         n <- nrow
  1613.     p <- ncol
  1614.     y <- array(0, c(n, p))
  1615.     y[1 + 0:(min(n, p) - 1) * (n + 1)] <- x
  1616.     y
  1617. }
  1618. "diag<-" <-
  1619. function(x, value)
  1620. {
  1621.     dx <- dim(x)
  1622.     if(length(dx) != 2 || prod(dx) != length(x))
  1623.         stop("only matrix diagonals can be replaced")
  1624.     i <- 1:min(dx)
  1625.     if(length(value) != 1 && length(value) != length(i))
  1626.         stop("replacement diagonal has wrong length")
  1627.     x[cbind(i, i)] <- value
  1628.     x
  1629. }
  1630. "diff" <-
  1631. function (x, lag = 1, differences = 1) 
  1632. {
  1633.     ismat <- is.matrix(x)
  1634.     if (ismat) 
  1635.         xlen <- dim(x)[1]
  1636.     else xlen <- length(x)
  1637.     if (lag < 1 | differences < 1) 
  1638.         stop("Bad value for lag or differences")
  1639.     if (lag * differences >= xlen) 
  1640.         return(x[0])
  1641.     r <- x
  1642.     s <- 1:lag
  1643.     if (is.matrix(r)) {
  1644.         for (i in 1:differences) {
  1645.             rlen <- dim(r)[1]
  1646.             r <- r[-s, , drop = FALSE] - r[-(rlen + 1 - s), , drop = FALSE]
  1647.         }
  1648.     }
  1649.     else for (i in 1:differences) {
  1650.         r <- r[-s] - r[-(length(r) + 1 - s)]
  1651.     }
  1652.     xtsp <- attr(x, "tsp")
  1653.     if (is.null(xtsp)) r
  1654.     else ts(r, end = xtsp[2], freq = xtsp[3])
  1655. }
  1656. dexp <- function(x, rate=1) .Internal(dexp(x, 1/rate))
  1657. pexp <- function(q, rate=1) .Internal(pexp(q, 1/rate))
  1658. qexp <- function(p, rate=1) .Internal(qexp(p, 1/rate))
  1659. rexp <- function(n, rate=1) .Internal(rexp(n, 1/rate))
  1660. dunif <- function(x, min=0, max=1) .Internal(dunif(x, min, max))
  1661. punif <- function(q, min=0, max=1) .Internal(punif(q, min, max))
  1662. qunif <- function(p, min=0, max=1) .Internal(qunif(p, min, max))
  1663. runif <- function(n, min=0, max=1) .Internal(runif(n, min, max))
  1664. dnorm <- function(x, mean=0, sd=1) .Internal(dnorm(x, mean, sd))
  1665. pnorm <- function(q, mean=0, sd=1) .Internal(pnorm(q, mean, sd))
  1666. qnorm <- function(p, mean=0, sd=1) .Internal(qnorm(p, mean, sd))
  1667. rnorm <- function(n, mean=0, sd=1) .Internal(rnorm(n, mean, sd))
  1668. dcauchy <- function(x, location=0, scale=1) .Internal(dcauchy(x, location, scale
  1669. ))
  1670. pcauchy <- function(q, location=0, scale=1) .Internal(pcauchy(q, location, scale
  1671. ))
  1672. qcauchy <- function(p, location=0, scale=1) .Internal(qcauchy(p, location, scale
  1673. ))
  1674. rcauchy <- function(n, location=0, scale=1) .Internal(rcauchy(n, location, scale
  1675. ))
  1676. dgamma <- function(x, shape, scale=1) .Internal(dgamma(x, shape, scale))
  1677. pgamma <- function(q, shape, scale=1) .Internal(pgamma(q, shape, scale))
  1678. qgamma <- function(p, shape, scale=1) .Internal(qgamma(p, shape, scale))
  1679. rgamma <- function(n, shape, scale=1) .Internal(rgamma(n, shape, scale))
  1680. dlnorm <- function(x, meanlog=0, sdlog=1) .Internal(dlnorm(x, meanlog, sdlog))
  1681. plnorm <- function(q, meanlog=0, sdlog=1) .Internal(plnorm(q, meanlog, sdlog))
  1682. qlnorm <- function(p, meanlog=0, sdlog=1) .Internal(qlnorm(p, meanlog, sdlog))
  1683. rlnorm <- function(n, meanlog=0, sdlog=1) .Internal(rlnorm(n, meanlog, sdlog))
  1684. dlogis <- function(x, location=0, scale=1) .Internal(dlogis(x, location, scale))
  1685. plogis <- function(q, location=0, scale=1) .Internal(plogis(q, location, scale))
  1686. qlogis <- function(p, location=0, scale=1) .Internal(qlogis(p, location, scale))
  1687. rlogis <- function(n, location=0, scale=1) .Internal(rlogis(n, location, scale))
  1688. dweibull <- function(x, shape, scale=1) .Internal(dweibull(x, shape, scale))
  1689. pweibull <- function(q, shape, scale=1) .Internal(pweibull(q, shape, scale))
  1690. qweibull <- function(p, shape, scale=1) .Internal(qweibull(p, shape, scale))
  1691. rweibull <- function(n, shape, scale=1) .Internal(rweibull(n, shape, scale))
  1692. "dotplot" <-
  1693. function (x, labels = NULL, groups = NULL, gdata = NULL, cex = par("cex"), 
  1694.         pch = 21, gpch = 21, bg = par("bg"), color = par("fg"), 
  1695.         gcolor = par("fg"), ...) 
  1696. {
  1697.         opar <- par("mar", "cex", "yaxs")
  1698.         on.exit(par(opar))
  1699.         par(cex = cex, yaxs = "i")
  1700.         if (is.matrix(x)) {
  1701.                 if (is.null(labels)) 
  1702.                         labels <- rownames(x)
  1703.                 if (is.null(labels)) 
  1704.                         labels <- as.character(1:nrow(x))
  1705.                 labels <- rep(labels, length = length(x))
  1706.                 if (is.null(groups)) 
  1707.                         groups <- col(x, as.factor = TRUE)
  1708.                 glabels <- levels(groups)
  1709.         }
  1710.         else {
  1711.                 if (is.null(labels)) 
  1712.                         labels <- names(x)
  1713.                 if (!is.null(groups)) 
  1714.                         glabels <- levels(groups)
  1715.                 else glabels <- NULL
  1716.         }
  1717.         linch <- 0
  1718.         ginch <- 0
  1719.         goffset <- 0
  1720.         if (!is.null(labels)) 
  1721.                 linch <- max(strwidth(labels, "inch"), na.rm = TRUE)
  1722.         if (!is.null(glabels)) {
  1723.                 ginch <- max(strwidth(glabels, "inch"), na.rm = TRUE)
  1724.                 goffset <- 0.4
  1725.         }
  1726.         if (!(is.null(labels) && is.null(glabels))) {
  1727.                 nmai <- par("mai")
  1728.                 nmai[2] <- nmai[4] + max(linch + goffset, ginch) + 
  1729.                         0.1
  1730.                 par(mai = nmai)
  1731.         }
  1732.         if (is.null(groups)) {
  1733.                 o <- 1:length(x)
  1734.                 y <- 1:length(x)
  1735.                 ylim <- c(0, length(x) + 1)
  1736.         }
  1737.         else {
  1738.                 o <- rev(order(codes(groups)))
  1739.                 x <- x[o]
  1740.                 groups <- groups[o]
  1741.                 offset <- cumsum(c(0, diff(codes(groups)[o])))
  1742.                 y <- 1:length(x) + 2 * offset
  1743.                 ylim <- range(0, y + 2)
  1744.         }
  1745.         plot.new()
  1746.         plot.window(xlim = range(x, na.rm = T), ylim = ylim, 
  1747.                 log = "")
  1748.         box()
  1749.         xmin <- par("usr")[1]
  1750.         if (!is.null(labels)) {
  1751.                 luser <- max(strwidth(labels, "user"), na.rm = TRUE)
  1752.                 loffset <- luser + xinch(0.1)
  1753.                 text(rep(xmin - loffset, length(x)), y, labels[o], 
  1754.                         xpd = TRUE, adj = 0, col = color, ...)
  1755.         }
  1756.         abline(h = y, lty = "dotted")
  1757.         points(x, y, pch = pch, col = color, bg = bg)
  1758.         if (!is.null(groups)) {
  1759.                 gpos <- rev(cumsum(tapply(groups, groups, length) + 
  1760.                         2) - 1)
  1761.                 guser <- max(strwidth(glabels, "user"), na.rm = TRUE)
  1762.                 goffset <- max(luser + xinch(goffset), guser, 
  1763.                         na.rm = TRUE) + xinch(0.1)
  1764.                 text(rep(xmin - goffset, nlevels(groups)), gpos, 
  1765.                         glabels, xpd = TRUE, adj = 0, col = gcolor, 
  1766.                         ...)
  1767.                 if (!is.null(gdata)) {
  1768.                         abline(h = gpos, lty = "dotted")
  1769.                         points(gdata, gpos, pch = gpch, col = gcolor, 
  1770.                                 bg = bg, ...)
  1771.                 }
  1772.         }
  1773.         axis(1)
  1774.         invisible()
  1775. }
  1776. dput <- function(x,file="")
  1777.         .Internal(dput(x,file))
  1778. dump <- function(list, fileout="dumpdata")
  1779. .Internal(dump(list, fileout))
  1780. dyn.load <- function(x)
  1781. {
  1782.     x <- as.character(x)
  1783.     y <- substr(x, 1, 1)
  1784.     if (y == "/") {
  1785.         .Internal(dyn.load(x))
  1786.     }
  1787.     else {
  1788.         .Internal(dyn.load(
  1789.         paste(system("pwd", intern = T), x, sep = "/", collapse="")))
  1790.     }
  1791. }
  1792. edit <- function(name=NULL, file="", editor=options()$editor) 
  1793.     .Internal(edit(name,file, editor))
  1794. vi <- function(name=NULL, file="") edit(name, file, editor="vi")
  1795. emacs <- function(name=NULL, file="") edit(name, file, editor="emacs")
  1796. xemacs <- function(name=NULL, file="") edit(name, file, editor="xemacs")
  1797. xedit <- function(name=NULL, file="") edit(name, file, editor="xedit")
  1798. eigen <- function(x) {
  1799.     if(!is.matrix(x) | nrow(x) != ncol(x))
  1800.         stop("non-square matrix in eigen")
  1801.     n <- nrow(x)
  1802.     z <- .C("eigen",
  1803.         n,
  1804.         as.double(x),
  1805.         vectors=matrix(0,n,n),
  1806.         values=double(n),
  1807.         double(n),
  1808.         ierr=integer(1))
  1809.     if(z$ierr)
  1810.         stop(paste("error code ",z$ierr," in eigen"))
  1811.     z[c("values", "vectors")]
  1812. }
  1813. environment <- function(fun=NULL) .Internal(environment(fun))
  1814. .GlobalEnv <- environment()
  1815. eval <-
  1816. function(expr, envir=sys.frame(sys.parent()))
  1817. {
  1818.     if(is.expression(expr))
  1819.         y<-for(i in 1:length(expr))
  1820.             .Internal(eval(expr[[i]],envir))
  1821.     else y<-.Internal(eval(expr, envir))
  1822.     y
  1823. }
  1824. quote <- function(x) substitute(x)
  1825. Recall <- function(...) .Internal(Recall(...))
  1826. exists <- function(x, where=NULL, envir=NULL, frame=NULL, mode="any", inherits=TRUE) {
  1827.     if(missing(envir) && !missing(frame)) 
  1828.         envir<-frame
  1829.     if(missing(envir) && !missing(where))
  1830.         envir<-where
  1831.     .Internal(exists(x,envir,mode,inherits))
  1832. }
  1833. factor <-
  1834. function(x, levels=sort(unique(x)), labels, exclude=NA, ordered=FALSE)
  1835. {
  1836.     if(length(x) == 0) return(character(0))
  1837.     if(length(exclude) > 0) {
  1838.         exclude <- as.vector(exclude, typeof(x))
  1839.         levels <- levels[is.na(match(levels, exclude))]
  1840.     }
  1841.     x <- .Internal(factor(match(x, levels), length(levels), ordered))
  1842.     if(missing(labels)) levels(x) <- levels
  1843.     else levels(x) <- labels
  1844.     x
  1845. }
  1846. as.factor <-
  1847. function(x, ordered=FALSE)
  1848. {
  1849.     test <- if(ordered) is.ordered else is.factor
  1850.         if(!test(x)) {
  1851.                 levs <- sort(unique(x))
  1852.                 x <- .Internal(factor(match(x, levs), length(levs), ordered))
  1853.                 levels(x) <- levs
  1854.         }
  1855.         x
  1856. }
  1857. ordered <-
  1858. function(x, levels=sort(unique(x)), labels, exclude=NA, ordered=TRUE)
  1859. {
  1860.     if(length(exclude) > 0) {
  1861.         exclude <- as.vector(exclude, typeof(x))
  1862.         levels <- levels[is.na(match(levels, exclude))]
  1863.     }
  1864.     x <- .Internal(factor(match(x, levels), length(levels), ordered))
  1865.     if(missing(labels)) levels(x) <- levels
  1866.     else levels(x) <- labels
  1867.     x
  1868. }
  1869. "family" <-
  1870. function(x, ...)
  1871. UseMethod("family")
  1872. "print.family" <-
  1873. function(x, ...)
  1874. {
  1875.     cat("\nFamily:", x$family, "\n")
  1876.     cat("Link function:", x$link, "\n\n") 
  1877. }
  1878. "power" <-
  1879. function(lambda = 1)
  1880. {
  1881.     if(lambda <= 0)
  1882.         return("log")
  1883.     return(lambda)
  1884. }
  1885. # this function is used with the glm function
  1886. # given a link it returns a link function, an inverse link
  1887. # function and the derivative dmu/deta
  1888. # Written by Simon Davies Dec 1995
  1889. ## Modified by Thomas Lumley 26 Apr 97
  1890. ## added valideta(eta) function returning TRUE if all of eta
  1891. ## is in the domain of linkinv
  1892. "make.link" <-
  1893. function (link) 
  1894. {
  1895.     recognise <- FALSE
  1896.     if (link == "logit") {
  1897.         linkfun <- function(mu) log(mu/(1 - mu))
  1898.         linkinv <- function(eta) exp(eta)/(1 + exp(eta))
  1899.         mu.eta <- function(eta) exp(eta)/(1 + exp(eta))^2
  1900.         valideta <- function(eta) TRUE
  1901.         recognise <- TRUE
  1902.     }
  1903.     if (link == "probit") {
  1904.         linkfun <- function(mu) qnorm(mu)
  1905.         linkinv <- pnorm
  1906.         mu.eta <- function(eta) 0.3989422 * exp(-0.5 * eta^2)
  1907.         valideta <- function(eta) TRUE
  1908.         recognise <- TRUE
  1909.     }
  1910.     if (link == "cloglog") {
  1911.         linkfun <- function(mu) log(-log(1 - mu))
  1912.         linkinv <- function(eta) 1 - exp(-exp(eta))
  1913.         mu.eta <- function(eta) exp(eta) * exp(-exp(eta))
  1914.         valideta <- function(eta) TRUE
  1915.         recognise <- TRUE
  1916.     }
  1917.     if (link == "identity") {
  1918.         linkfun <- function(mu) mu
  1919.         linkinv <- function(eta) eta
  1920.         mu.eta <- function(eta) rep(1, length(eta))
  1921.         valideta <- function(eta) TRUE
  1922.         recognise <- TRUE
  1923.     }
  1924.     if (link == "log") {
  1925.         linkfun <- function(mu) log(mu)
  1926.         linkinv <- function(eta) exp(eta)
  1927.         mu.eta <- function(eta) exp(eta)
  1928.         valideta <- function(eta) TRUE
  1929.         recognise <- TRUE
  1930.     }
  1931.     if (link == "sqrt") {
  1932.         linkfun <- function(mu) mu^0.5
  1933.         linkinv <- function(eta) eta^2
  1934.         mu.eta <- function(eta) 2 * eta
  1935.         valideta <- function(eta) all(eta>0)
  1936.         recognise <- TRUE
  1937.     }
  1938.     if (link == "1/mu^2") {
  1939.         linkfun <- function(mu) 1/mu^2
  1940.         linkinv <- function(eta) 1/eta^0.5
  1941.         mu.eta <- function(eta) -1/(2 * eta^1.5)
  1942.         valideta <- function(eta) all(eta>0)
  1943.         recognise <- TRUE
  1944.     }
  1945.     if (link == "inverse") {
  1946.         linkfun <- function(mu) 1/mu
  1947.         linkinv <- function(eta) 1/eta
  1948.         mu.eta <- function(eta) -1/(eta^2)
  1949.         valideta <- function(eta) all(eta!=0)
  1950.         recognise <- TRUE
  1951.     }
  1952.     if (!is.na(as.numeric(link))) {
  1953.         lambda <- as.numeric(link)
  1954.         linkfun <- function(mu) mu^lambda
  1955.         linkinv <- function(eta) eta^(1/lambda)
  1956.         mu.eta <- function(eta) (1/lambda) * eta^(1/lambda - 1)
  1957.         valideta <- function(eta) all(eta>0)
  1958.         recognise <- TRUE
  1959.     }
  1960.     if (!recognise) 
  1961.         stop(paste(link, "link not recognised"))
  1962.     return(list(linkfun = linkfun,
  1963.         linkinv = linkinv,
  1964.         mu.eta = mu.eta,
  1965.         valideta=valideta))
  1966. }
  1967. "poisson" <-
  1968. function (link = "log") 
  1969. {
  1970.     linktemp <- substitute(link)
  1971.     #this is a function used in the glm function
  1972.     #it holds everything personal to the family
  1973.     #converts link into character string
  1974.     if (!is.character(linktemp)) {
  1975.         linktemp <- deparse(linktemp)
  1976.         if (linktemp == "link") 
  1977.             linktemp <- eval(link)
  1978.     }
  1979.     if (any(linktemp == c("log", "identity", "sqrt"))) 
  1980.         stats <- make.link(linktemp)
  1981.     else stop(paste(linktemp, "link not available for poisson",
  1982.             "family, available links are \"identity\", ",
  1983.             "\"log\" and \"sqrt\""))
  1984.     variance <- function(mu) mu
  1985.     validmu <- function(mu) all(mu>0)
  1986.     dev.resids <- function(y, mu, wt)
  1987.         2 * wt * (y * log(ifelse(y == 0, 1, y/mu)) - (y - mu))
  1988.     initialize <- expression({
  1989.         if (any(y < 0)) 
  1990.             stop(paste("Negative values not allowed for",
  1991.                 "the Poisson family"))
  1992.         n <- rep(1, nobs)
  1993.         mustart <- y + 0.1
  1994.     })
  1995.     family <- list(family = "poisson",
  1996.             link = linktemp,
  1997.             linkfun = stats$linkfun,
  1998.             linkinv = stats$linkinv,
  1999.             variance = variance,
  2000.             dev.resids = dev.resids,
  2001.             mu.eta = stats$mu.eta,
  2002.             initialize = initialize,
  2003.             validmu = validmu,
  2004.             valideta = stats$valideta)
  2005.     class(family) <- "family"
  2006.     return(family)
  2007. }
  2008. "gaussian" <-
  2009. function () 
  2010. {
  2011.     stats <- make.link("identity")
  2012.     # this is a function used in the glm function
  2013.     # it holds everything personal to the family
  2014.     variance <- function(mu) rep(1, length(mu))
  2015.     dev.resids <- function(y, mu, wt) wt * ((y - mu)^2)
  2016.     initialize <- expression({
  2017.         n <- rep(1, nobs)
  2018.         mustart <- y
  2019.     })
  2020.     validmu <- function(mu) TRUE
  2021.     family <- list(family = "gaussian",
  2022.             link = "identity",
  2023.             linkfun = stats$linkfun,
  2024.             linkinv = stats$linkinv,
  2025.             variance = variance,
  2026.             dev.resids = dev.resids,
  2027.             mu.eta = stats$mu.eta,
  2028.             initialize = initialize,
  2029.             validmu = validmu,
  2030.             valideta = stats$valideta)
  2031.     class(family) <- "family"
  2032.     return(family)
  2033. }
  2034. "binomial" <-
  2035. function (link = "logit") 
  2036. {
  2037.     linktemp <- substitute(link)
  2038.     # this is a function used in the glm function
  2039.     # it holds everything personal to the family
  2040.     # converts link into character string
  2041.     if (!is.character(linktemp)) {
  2042.         linktemp <- deparse(linktemp)
  2043.         if (linktemp == "link") 
  2044.             linktemp <- eval(link)
  2045.     }
  2046.     if (any(linktemp == c("logit", "probit", "cloglog"))) 
  2047.         stats <- make.link(linktemp)
  2048.     else stop(paste(linktemp, "link not available for binomial",
  2049.         "family, available links are \"logit\", ",
  2050.         "\"probit\" and \"cloglog\""))
  2051.     variance <- function(mu) mu * (1 - mu)
  2052.     validmu <- function(mu) all(mu>0) && all(mu<1)
  2053.     dev.resids <- function(y, mu, wt)
  2054.         2 * wt * (y * log(ifelse(y == 0, 1, y/mu)) +
  2055.         (1 - y) * log(ifelse(y == 1, 1, (1 - y)/(1 - mu))))
  2056.     initialize <- expression({
  2057.         if (NCOL(y) == 1) {
  2058.             n <- rep(1, nobs)
  2059.             if (any(y < 0 | y > 1)) 
  2060.                 stop("y values must be 0 <= y <= 1")
  2061.         }
  2062.         else if (NCOL(y) == 2) {
  2063.             n <- y[, 1] + y[, 2]
  2064.             y <- y[, 1]/n
  2065.             weights <- weights * n
  2066.         }
  2067.         else stop(paste("For the binomial family, y must be",
  2068.             "a vector of 0 and 1\'s or a 2 column",
  2069.             "matrix where col 1 is no. successes",
  2070.             "and col 2 is no. failures"))
  2071.         mustart <- (n * y + 0.5)/(n + 1)
  2072.     })
  2073.     family <- list(family = "binomial",
  2074.             link = linktemp,
  2075.             linkfun = stats$linkfun,
  2076.             linkinv = stats$linkinv,
  2077.             variance = variance,
  2078.             dev.resids = dev.resids,
  2079.             mu.eta = stats$mu.eta,
  2080.             initialize = initialize,
  2081.             validmu = validmu,
  2082.             valideta = stats$valideta)
  2083.     class(family) <- "family"
  2084.     return(family)
  2085. }
  2086. "Gamma" <-
  2087. function (link = "inverse") 
  2088. {
  2089.     linktemp <- substitute(link)
  2090.     #this is a function used in the glm function
  2091.     #it holds everything personal to the family
  2092.     #converts link into character string
  2093.     if (!is.character(linktemp)) {
  2094.         linktemp <- deparse(linktemp)
  2095.         if (linktemp == "link") 
  2096.             linktemp <- eval(link)
  2097.     }
  2098.     if (any(linktemp == c("inverse", "log", "identity"))) 
  2099.         stats <- make.link(linktemp)
  2100.     else stop(paste(linktemp, "link not available for gamma",
  2101.         "family, available links are \"inverse\", ",
  2102.         "\"log\" and \"identity\""))
  2103.     variance <- function(mu) mu^2
  2104.     validmu <- function(mu) all(mu>0) 
  2105.     dev.resids <- function(y, mu, wt)
  2106.         -2 * wt * (log(ifelse(y == 0, 1, y/mu)) - (y - mu)/mu)
  2107.     initialize <- expression({
  2108.         if (any(y < 0)) 
  2109.             stop(paste("Negative values not",
  2110.                 "allowed for the gamma family"))
  2111.         n <- rep(1, nobs)
  2112.         mustart <- y
  2113.     })
  2114.     family <- list(family = "Gamma",
  2115.             link = linktemp,
  2116.             linkfun = stats$linkfun,
  2117.             linkinv = stats$linkinv,
  2118.             variance = variance,
  2119.             dev.resids = dev.resids,
  2120.             mu.eta = stats$mu.eta,
  2121.             initialize = initialize,
  2122.             validmu = validmu,
  2123.             valideta = stats$valideta)
  2124.     class(family) <- "family"
  2125.     return(family)
  2126. }
  2127. "inverse.gaussian" <-
  2128. function()
  2129. {
  2130.     stats <- make.link("1/mu^2")
  2131.     variance <- function(mu) mu^3
  2132.     dev.resids <- function(y, mu, wt)  wt*((y - mu)^2)/(y*mu^2)
  2133.     initialize <- expression({
  2134.             if(any(y <= 0))
  2135.                 stop(paste("Positive values only allowed for",
  2136.                     "the inverse.gaussian family"))
  2137.             n <- rep(1, nobs)
  2138.             mustart <- y
  2139.             })
  2140.     validmu <- function(mu) TRUE
  2141.     family <- list(family = "inverse.gaussian",
  2142.             link = "1/mu^2",
  2143.             linkfun = stats$linkfun,
  2144.             linkinv = stats$linkinv,
  2145.             variance = variance,
  2146.             dev.resids = dev.resids,
  2147.             mu.eta = stats$mu.eta,
  2148.             initialize = initialize,
  2149.             validmu = validmu,
  2150.             valideta = stats$valideta)
  2151.     class(family) <- "family"
  2152.     return(family)
  2153. }
  2154. "quasi" <-
  2155. function (link = "identity", variance = "constant") 
  2156. {
  2157.     linktemp <- substitute(link)
  2158.     #this is a function used in the glm function
  2159.     #it holds everything personal to the family
  2160.     #converts link into character string
  2161.     if (is.expression(linktemp)) 
  2162.         linktemp <- eval(linktemp)
  2163.     if (!is.character(linktemp)) {
  2164.         linktemp <- deparse(linktemp)
  2165.         if (linktemp == "link") 
  2166.             linktemp <- eval(link)
  2167.     }
  2168.     stats <- make.link(linktemp)
  2169.     #converts variance into character string
  2170.     variancetemp <- substitute(variance)
  2171.     if (!is.character(variancetemp)) {
  2172.         variancetemp <- deparse(variancetemp)
  2173.         if (linktemp == "variance") 
  2174.             variancetemp <- eval(variance)
  2175.     }
  2176.     if (!any(variancetemp == c("mu(1-mu)",
  2177.         "mu", "mu^2", "mu^3", "constant"))) 
  2178.         stop(paste(variancetemp, "not recognised, possible variances",
  2179.             "are \"mu(1-mu)\", \"mu\", \"mu^2\", \"mu^3\" and",
  2180.             "\"constant\""))
  2181.     if (variancetemp == "constant") {
  2182.         variance <- function(mu) rep(1, length(mu))
  2183.         dev.resids <- function(y, mu, wt) wt * ((y - mu)^2)
  2184.         validmu <-function(mu) TRUE
  2185.     }
  2186.     if (variancetemp == "mu(1-mu)") {
  2187.         variance <- function(mu) mu * (1 - mu)
  2188.         validmu <-function(mu) all(mu>0) && all(mu<1)
  2189.         dev.resids <- function(y, mu, wt)
  2190.             2 * wt * (y * log(ifelse(y == 0, 1,
  2191.             y/mu)) + (1 - y) * log(ifelse(y == 1, 1, (1 - y)/(1 - mu))))
  2192.     }
  2193.     if (variancetemp == "mu") {
  2194.         variance <- function(mu) mu
  2195.         validmu<-function(mu) all(mu>0)
  2196.         dev.resids <- function(y, mu, wt)
  2197.             2 * wt * (y * log(ifelse(y == 0, 1, y/mu)) - (y - mu))
  2198.     }
  2199.     if (variancetemp == "mu^2") {
  2200.         variance <- function(mu) mu^2
  2201.         validmu<-function(mu) all(mu!=0)
  2202.         dev.resids <- function(y, mu, wt)
  2203.             -2 * wt * (log(y/mu) - (y - mu)/mu)
  2204.     }
  2205.     if (variancetemp == "mu^3") {
  2206.         variance <- function(mu) mu^3
  2207.         validmu <-function(mu) all(mu>0)
  2208.         dev.resids <- function(y, mu, wt) wt * ((y - mu)^2)/(y * mu^2)
  2209.     }
  2210.     initialize <- expression({
  2211.         n <- rep(1, nobs)
  2212.         mustart <- y
  2213.     })
  2214.     family <- list(family = "quasi",
  2215.             link = linktemp,
  2216.             linkfun = stats$linkfun,
  2217.             linkinv = stats$linkinv,
  2218.             variance = variance,
  2219.             dev.resids = dev.resids,
  2220.             mu.eta = stats$mu.eta,
  2221.             initialize = initialize,
  2222.             validmu = validmu,
  2223.             valideta = stats$valideta)
  2224.     class(family) <- "family"
  2225.     return(family)
  2226. }
  2227. fft <- function(z, inverse=FALSE)
  2228. .Internal(fft(z, inverse))
  2229. mvfft <- function(z, inverse=FALSE)
  2230. .Internal(mvfft(z, inverse))
  2231. nextn <- function(n, factors=c(2,3,5))
  2232. .Internal(nextn(n, factors))
  2233. convolve <-
  2234. function(x, y, conj=T) {
  2235.     if(length(x) != length(y))
  2236.         stop("length mismatch in convolution")
  2237.     if(conj)
  2238.         Re(fft(fft(x)*Conj(fft(y)),inv=T))/length(x)
  2239.     else
  2240.         Re(fft(fft(x)*fft(y),inv=T))/length(x)
  2241. }
  2242. fivenum <- function(x, na.rm=TRUE)
  2243. {
  2244.     xna <- is.na(x)
  2245.     if(na.rm) x <- x[!xna]
  2246.     else if(any(xna)) return(rep(NA,5))
  2247.     x <- sort(x)
  2248.     n <- length(x)
  2249.     if(n == 0) rep(NA,5)
  2250.     else {
  2251.         d <- c(1, 0.5*floor(0.5*(n+3)), 0.5*(n+1),
  2252.             n+1-0.5*floor(0.5*(n+3)), n)
  2253.         0.5*(x[floor(d)]+x[ceiling(d)])
  2254.     }
  2255. }
  2256. fix <- function(x) {
  2257.     subx <- substitute(x)
  2258.     if( is.name(subx) )
  2259.         subx<-deparse(subx)
  2260.     if (!is.character(subx) || length(subx) != 1)
  2261.         stop("fix requires a name")
  2262.     if(exists(subx, inherits=TRUE))
  2263.         x <- edit(get(subx))
  2264.     else
  2265.         stop(paste("no object named \"", subx, "\" to edit",sep=""))
  2266.     assign(subx, x, .GlobalEnv)
  2267. }
  2268. formals <- function(fun=sys.function(sys.parent())) {
  2269.     if(is.character(fun))
  2270.         fun <- get(fun, mode = "function")
  2271.     .Internal(formals(fun))
  2272. }
  2273. body <- function(fun=sys.function(sys.parent())) {
  2274.     if(is.character(fun))
  2275.         fun <- get(fun, mode = "function")
  2276.     .Internal(body(fun))
  2277. }
  2278. "formatC" <-
  2279. function (x, digits=NULL, width=max(0, digits) + 1, format=NULL, 
  2280.     flag="", mode=NULL) 
  2281. {
  2282.     # Copyright (C) Martin Maechler, 1994
  2283.     bl.string <- function(no) paste(rep(" ", no), collapse = "")
  2284.     if (is.null(x)) return("")
  2285.     n <- length(x)
  2286.     if (missing(mode)) 
  2287.         mode <- storage.mode(x)
  2288.     else if (any(mode == c("real", "integer"))) 
  2289.         storage.mode(x) <- mode
  2290.     else stop("\"mode\" must be \"real\" or \"integer\"")
  2291.     if (mode == "character" || (!is.null(format) && format == "s")) {
  2292.         if (mode != "character") {
  2293.             warning("should give \"character\" argument for format=\"s\" -- COERCE")
  2294.             x <- as.character(x)
  2295.         }
  2296.         nc <- nchar(x)
  2297.         if (width < 0) {
  2298.             flag <- "-"
  2299.             width <- -width
  2300.         }
  2301.         pad <- sapply(pmax(0, width - nc), bl.string)
  2302.         ## for R <= 0.16 (incompatibility to S):
  2303.         if(is.list(pad)) pad <- ""
  2304.         if (flag == "-") 
  2305.             return(paste(x, pad, sep = ""))
  2306.         else    return(paste(pad, x, sep = ""))
  2307.     }
  2308.     some.special <- !all(Ok <- is.finite(x))
  2309.     if (some.special) {
  2310.         nQ <- nchar(rQ <- as.character(x[!Ok]))
  2311.         nX <- pmax(width - nQ, 0)
  2312.         #-- number of characters to add
  2313.         x[!Ok] <- 0
  2314.     }
  2315.     if (missing(format) || is.null(format)) 
  2316.         format <- if (mode == "integer") 
  2317.             "d"
  2318.         else "g"
  2319.     else {
  2320.         if (any(format == c("f", "e", "E", "g", "G"))) {
  2321.             if (mode == "integer") 
  2322.                 mode <- storage.mode(x) <- "single"
  2323.         }
  2324.         else if (format == "d") {
  2325.             if (mode != "integer") 
  2326.                 mode <- storage.mode(x) <- "integer"
  2327.         }
  2328.         else stop("\"format\" must be in {\"f\",\"e\",\"E\",\"g\",\"G\", \"s\"}" )
  2329.     }
  2330.     if (missing(digits) || is.null(digits)) 
  2331.         digits <- if (mode == "integer") 
  2332.             2
  2333.         else 4
  2334.     if (width == 0) 
  2335.         stop("\"width\" must not be 0")
  2336.     r <- .C("str_signif", 
  2337.         x = x, 
  2338.         n = n, 
  2339.         mode = as.character(mode), 
  2340.         width = as.integer(width), 
  2341.         digits = as.integer(digits), 
  2342.         format = as.character(format), 
  2343.         flag = as.character(flag), 
  2344.         result = rep(bl.string(abs(width) + 10), n)
  2345.     )$result
  2346.     if (some.special) 
  2347.         r[!Ok] <- rQ
  2348.     if (!is.null(x.atr <- attributes(x))) 
  2349.         attributes(r) <- x.atr
  2350.     r
  2351. }
  2352. get <- function(x, envir=NULL, mode="any", inherits=TRUE)
  2353. .Internal(get(x,envir,mode,inherits))
  2354. # gl function of glim
  2355. gl <- function (n, k, length, labels=1:n, ordered=FALSE)
  2356.     factor(rep(rep(1:n,rep(k,n)), length=length),
  2357.         labels=labels, ordered=ordered)
  2358. # This function fits a generalized linear model via
  2359. # iteratively reweighted least squares for any family.
  2360. # Written by Simon Davies, Dec 1995
  2361. # glm.fit modified by Thomas Lumley, Apr 1997
  2362. glm <- function(formula, family=gaussian, data, weights=NULL,
  2363.     subset=NULL, na.action=na.fail, start=NULL, offset=NULL,
  2364.     control=glm.control(epsilon=0.0001, maxit=10, trace=FALSE),
  2365.     model=TRUE, method=glm.fit, x=FALSE, y=TRUE)
  2366. {
  2367.     call <- sys.call()
  2368.     # family
  2369.     if(is.character(family)) family <- get(family)
  2370.     if(is.function(family)) family <- family()
  2371.     if(is.null(family$family)) stop("family not recognised")
  2372.     # extract x, y, etc from the model formula and frame
  2373.     mt <- terms(formula)
  2374.     if(missing(data)) data <- sys.frame(sys.parent())
  2375.         mf <- match.call()
  2376.         mf$family <- mf$start <- mf$control <- mf$maxit <- NULL
  2377.     mf$model <- mf$method <- mf$x <- mf$y <- NULL
  2378.         mf$use.data <- TRUE
  2379.         mf[[1]] <- as.name("model.frame")
  2380.         mf <- eval(mf, sys.frame(sys.parent()))
  2381.     X <- model.matrix(mt, mf)
  2382.     Y <- model.response(mf, "numeric")
  2383.     weights <- model.weights(mf)
  2384.     offset <- model.offset(mf)
  2385.     # check weights and offset
  2386.     if( !is.null(weights) && any(weights<0) )
  2387.         stop("Negative wts not allowed")
  2388.     if(!is.null(offset) && length(offset) != NROW(Y))
  2389.         stop(paste("Number of offsets is", length(offset),
  2390.             ", should equal", NROW(Y), "(number of observations)"))
  2391.     # fit model via iterative reweighted least squares
  2392.     fit <- method(x=X, y=Y, weights=weights, start=start,
  2393.         offset=offset, family=family, control=control)
  2394.     # output
  2395.     if(model) fit$model <- mf
  2396.     if(x) fit$x <- X
  2397.     else fit$x <- NULL
  2398.     if(!y) fit$y <- NULL
  2399.     fit <- c(fit, list(call=call, formula=formula, x=x, terms=mt, data=data,
  2400.         offset=offset, control=control, method=method))
  2401.     class(fit) <- c("glm", "lm")
  2402.     return(fit)
  2403. }
  2404. glm.control <- function(epsilon = 0.0001, maxit = 10, trace = FALSE)
  2405. {
  2406.     if(epsilon <= 0)
  2407.         stop("value of epsilon must be > 0")
  2408.     if(maxit <= 0)
  2409.         stop("maximum number of iterations must be > 0")
  2410.     return(list(epsilon = epsilon, maxit = maxit, trace = trace))
  2411. }
  2412. ## Modified by Thomas Lumley 26 Apr 97
  2413. ## Added boundary checks and step halving
  2414. ## Modified detection of fitted 0/1 in binomial
  2415. "glm.fit" <-
  2416. function (x, y, weights = rep(1, nobs), start = NULL, offset = rep(0, nobs),
  2417. family = gaussian(), control = glm.control(), intercept = TRUE) 
  2418. {
  2419.     xnames <- dimnames(x)[[2]]
  2420.     ynames <- names(y)
  2421.     conv <- FALSE
  2422.     nobs <- NROW(y)
  2423.     nvars <- NCOL(x)
  2424.     # define weights and offset if needed
  2425.     if (is.null(weights)) 
  2426.         weights <- rep(1, nobs)
  2427.     if (is.null(offset)) 
  2428.         offset <- rep(0, nobs)
  2429.     # get family functions
  2430.     variance <- family$variance
  2431.     dev.resids <- family$dev.resids
  2432.     linkinv <- family$linkinv
  2433.     mu.eta <- family$mu.eta
  2434.     valideta<-family$valideta
  2435.     if (is.null(valideta)) valideta<-function(eta) TRUE
  2436.     validmu<-family$validmu
  2437.     if (is.null(validmu)) validmu<-function(mu) TRUE
  2438.     eval(family$initialize, sys.frame(sys.nframe()))
  2439.     if (NCOL(y) > 1) 
  2440.         stop("y must be univariate unless binomial")
  2441.     # calculates the first estimate of eta and mu
  2442.     if (is.null(start)) {
  2443.       start<-c(0.5,rep(0,nvars-1))
  2444.       linkfun <- family$linkfun
  2445.       if (validmu(mustart)){
  2446.         etastart <- linkfun(mustart)
  2447.         if (valideta(etastart)){
  2448.           z <- etastart + (y - mustart)/mu.eta(etastart) - offset
  2449.           w <- ((weights * mu.eta(etastart)^2)/variance(mustart))^0.5
  2450.           fit <- qr(x * w)
  2451.           start <- qr.coef(fit, w * z)
  2452.           start[is.na(start)] <- 0
  2453.         }
  2454.       }
  2455.     }
  2456.       else if (length(start) != nvars) 
  2457.         stop(paste("Length of start should equal", nvars, "and correspond to initial coefs for", deparse(xnames)))
  2458.     if (NCOL(x) == 1) 
  2459.       eta <- as.vector(x * start)
  2460.       else eta <- as.vector(x %*% start)
  2461.     mu <- linkinv(eta + offset)
  2462.     if (!(validmu(mu) && valideta(eta)))
  2463.       stop("Can't find valid starting values: please specify with start=")
  2464.     # calculate initial deviance and coefficient
  2465.     devold <- sum(dev.resids(y, mu, weights))
  2466.     coefold <- start
  2467.     boundary<-FALSE
  2468.     # do iteration
  2469.     for (iter in 1:control$maxit) {
  2470.         mu.eta.val <- mu.eta(eta + offset)
  2471.         if (any(is.na(mu.eta.val))){
  2472.           mu.eta.val[is.na(mu.eta.val)]<-mu.eta(mu)[is.na(mu.eta.val)]
  2473.         }
  2474.         if (any(is.na(mu.eta.val)))
  2475.           stop("NAs in d(mu)/d(eta)")
  2476.         # calculate z and w using only values where mu.eta != 0
  2477.         good <- (mu.eta.val != 0)
  2478.         if (all(!good)) {
  2479.             conv <- FALSE
  2480.             warning("No observations informative at iteration",iter)
  2481.             break
  2482.         }
  2483.         z <- eta[good] + (y - mu)[good]/mu.eta.val[good]
  2484.         w <- ((weights * mu.eta.val^2)[good]/variance(mu)[good])^0.5
  2485.         x <- as.matrix(x)
  2486.         ngoodobs <- as.integer(nobs - sum(!good))
  2487.         ncols <- as.integer(1)
  2488.         # call linpack code
  2489.         fit <- .Fortran("dqrls", 
  2490.             qr = x[good, ] * w, 
  2491.             n = as.integer(ngoodobs), 
  2492.             p = nvars, 
  2493.             y = w * z, 
  2494.             ny = ncols, 
  2495.             tol = 1e-07, 
  2496.             coefficients = mat.or.vec(nvars, 1), 
  2497.             residuals = mat.or.vec(ngoodobs, 1), 
  2498.             effects = mat.or.vec(ngoodobs, 1), 
  2499.             rank = integer(1), 
  2500.             pivot = as.integer(1:nvars), 
  2501.             qraux = double(nvars), 
  2502.             work = double(2 * nvars)
  2503.         )
  2504.         # stop if not enough parameters
  2505.         if (nobs < fit$rank) 
  2506.             stop(paste("X matrix has rank", fit$rank, "but only", nobs, "observations"
  2507.             ))
  2508.         # if X matrix was not full rank then columns
  2509.         # were pivoted, hence we need to re-label the names
  2510.         if (fit$rank != nvars) {
  2511.             xnames <- xnames[fit$pivot]
  2512.             dimnames(fit$qr) <- list(NULL, xnames)
  2513.         }
  2514.         # calculate updated values of eta and mu with the new coef
  2515.         start <- coef <- fit$coefficients
  2516.         start[fit$pivot] <- coef
  2517.         if (nvars == 1) 
  2518.             eta[good] <- x[good] * start
  2519.         else eta[good] <- as.vector(x[good, ] %*% start)
  2520.         mu <- linkinv(eta + offset)
  2521.         if (family$family == "binomial") {
  2522.             if (any(mu == 1) || any(mu == 0)) 
  2523.                 warning("fitted probabilities of 0 or 1 occured")
  2524.             mu[mu == 1] <- 1 - 0.5 * control$epsilon/length(mu)
  2525.             mu[mu == 0] <- 0.5 * control$epsilon/length(mu)
  2526.         }
  2527.         if (family$family == "poisson") {
  2528.             if (any(mu == 0)) 
  2529.                 warning("fitted rates of 0 occured")
  2530.             mu[mu == 0] <- 0.5 * control$epsilon/length(mu)^2
  2531.         }
  2532.         dev <- sum(dev.resids(y, mu, weights))
  2533.         if (control$trace) 
  2534.             cat("Deviance =", dev, "Iterations -", iter, "\n")
  2535.         # check for divergence
  2536.         boundary<-FALSE
  2537.         if (any(is.na(dev)) || any(is.na(coef))) {
  2538.             warning("Step size truncated due to divergence")
  2539.             ii<-1
  2540.             while( (any(is.na(dev)) || any(is.na(start)))){
  2541.               if (ii>control$maxit) stop("Can't correct")
  2542.               ii<-ii+1
  2543.               start<-(start+coefold)/2
  2544.               if (nvars == 1) 
  2545.                 eta[good] <- x[good] * start
  2546.                 else eta[good] <- as.vector(x[good, ] %*% start)
  2547.               mu <- linkinv(eta + offset)
  2548.               dev <- sum(dev.resids(y, mu, weights))
  2549.             }
  2550.             boundary<-TRUE
  2551.             coef<-start
  2552.             if (control$trace) 
  2553.               cat("New Deviance =", dev, "\n")
  2554.               }
  2555.         ## check for fitted values outside domain.
  2556.         if (!(valideta(eta) && validmu(mu))) {
  2557.             warning("Step size truncated: out of bounds.")
  2558.             ii<-1
  2559.             while(!(valideta(eta) && validmu(mu))){
  2560.               if (ii>control$maxit) stop("Can't correct step size.")
  2561.               ii<-ii+1
  2562.               start<-(start+coefold)/2
  2563.               if (nvars == 1) 
  2564.                 eta[good] <- x[good] * start
  2565.                 else eta[good] <- as.vector(x[good, ] %*% start)
  2566.               mu <- linkinv(eta + offset)
  2567.             }
  2568.             boundary<-TRUE
  2569.             coef<-start
  2570.             dev <- sum(dev.resids(y, mu, weights))
  2571.             if (control$trace) 
  2572.               cat("New Deviance =", dev, "\n")
  2573.               }
  2574.         #check for convergence
  2575.         if (abs(dev - devold)/(0.1 + abs(dev)) < control$epsilon) {
  2576.           conv <- TRUE
  2577.           break
  2578.         }
  2579.           else {
  2580.             devold <- dev
  2581.             coefold <- coef
  2582.           }
  2583.           }
  2584.     if (!conv) 
  2585.       warning("Algorithm did not converge")
  2586.     if (boundary)
  2587.       warning("Algorithm stopped at boundary value")
  2588.                     # calculate residuals
  2589.     residuals <- rep(NA, nobs)
  2590.     ##     residuals[good] <- z - eta
  2591.     residuals[good]<-z-eta[good]
  2592.                     # name output
  2593.     fit$qr <- as.matrix(fit$qr)
  2594.     Rmat <- fit$qr[1:nvars, 1:nvars]
  2595.     Rmat <- as.matrix(Rmat)
  2596.     Rmat[row(Rmat) > col(Rmat)] <- 0
  2597.     names(coef) <- xnames
  2598.     colnames(fit$qr) <- xnames
  2599.     dimnames(Rmat) <- list(xnames, xnames)
  2600.     names(residuals) <- ynames
  2601.     names(mu) <- ynames
  2602.     names(eta) <- ynames
  2603.     names(w) <- ynames
  2604.     names(weights) <- ynames
  2605.     names(y) <- ynames
  2606.                     # calculate null deviance
  2607.     if (intercept) 
  2608.       wtdmu <- sum(weights * y)/sum(weights)
  2609.       else wtdmu <- linkinv(offset)
  2610.     nulldev <- sum(dev.resids(y, wtdmu, weights))
  2611.                     # calculate df
  2612.     nulldf <- nobs - as.numeric(intercept)
  2613.     resdf <- nobs - fit$rank - sum(weights == 0)
  2614.     qr <- list(qr = fit$qr, rank = fit$rank, qraux = fit$qraux)
  2615.     return(list(coefficients = coef, residuals = residuals, fitted.values = mu
  2616.             , effects = fit$effects, R = Rmat, rank = fit$rank, qr = qr, family = family
  2617.             , linear.predictors = eta, deviance = dev, null.deviance = nulldev, iter = iter
  2618.             , weights = w^2, prior.weights = weights, df.residual = resdf, df.null = nulldf
  2619.             , y = y,converged=conv,boundary=boundary))
  2620. }
  2621. print.glm <- function (x, digits = max(3, .Options$digits - 3),
  2622.     na.print="", ...)
  2623. {
  2624.     cat("\nCall: ", deparse(x$call), "\n\n")
  2625.     cat("Coefficients:\n")
  2626.     print.default(round(x$coefficients, digits), print.gap = 2)
  2627.     cat("\nDegrees of Freedom:", length(x$residuals), "Total;",
  2628.          x$df.residual, "Residual\n")
  2629.     cat("Null Deviance:", format(signif(x$null.deviance, digits)), "\n")
  2630.     cat("Residual Deviance:", format(signif(x$deviance, digits)), "\n")
  2631.     invisible(x)
  2632. }
  2633. anova.glm <- function(object, ..., test=NULL, na.action=na.omit)
  2634. {
  2635.     # check for multiple objects
  2636.     args <- function(...) nargs()
  2637.     if(args(...)) return(anova.glmlist(list(object, ...), test=test))
  2638.     # extract variables from model
  2639.     varlist <- attr(object$terms, "variables")
  2640.     if(!is.null(object$x) && !(is.logical(object$x) || 
  2641.         object$x==FALSE)) x <- object$x
  2642.     else {
  2643.         if(is.null(object$model)) {
  2644.             if(is.null(object$data))    
  2645.                 object$data <- sys.frame(sys.parent())
  2646.             object$model <- na.action(
  2647.                 model.frame(eval(varlist, object$data),
  2648.                     as.character(varlist[-1]), NULL))
  2649.         }
  2650.         x <- model.matrix(object$terms, object$model)
  2651.     }
  2652.     varseq <- attr(x, "assign")
  2653.     nvars <- max(varseq)
  2654.     resdev <- resdf <- NULL
  2655.     # if there is more than one explanatory variable then
  2656.     # recall glm.fit to fit variables sequentially
  2657.     if(nvars > 1) {
  2658.         for(i in 1:(nvars-1)) {
  2659.             # explanatory variables up to i are kept in the model
  2660.             tempx <- x[, varseq <= i]
  2661.             # use method from glm to find residual deviance
  2662.             # and df for each sequential fit
  2663.             method <- object$method
  2664.             fit <- method(x=tempx, y=object$y,
  2665.                 weights=object$prior.weights,
  2666.                 start=object$start,
  2667.                 offset=object$offset,
  2668.                 family=object$family,
  2669.                 control=object$control)
  2670.             resdev <- c(resdev, fit$deviance)
  2671.             resdf <- c(resdf, fit$df.residual)
  2672.         }
  2673.     }
  2674.     # add values from null and full model
  2675.     resdf <- c(object$df.null, resdf, object$df.residual)
  2676.     resdev <- c(object$null.deviance, resdev, object$deviance)
  2677.     # construct table and title
  2678.     table <- cbind(c(NA, -diff(resdf)), c(NA, -diff(resdev)), resdf, resdev)
  2679.     dimnames(table) <- list(c("NULL", attr(object$terms, "term.labels")),
  2680.                 c("Df", "Deviance", "Resid. Df", "Resid. Dev"))
  2681.     title <- paste("Analysis of Deviance Table", "\n\nModel: ",
  2682.         object$family$family, ", link: ", object$family$link,
  2683.         "\n\nResponse: ", as.character(varlist[-1])[1],
  2684.         "\n\nTerms added sequentially (first to last)\n\n", sep="")
  2685.     # calculate test statistics if needed
  2686.     if(!is.null(test))
  2687.         table <- stat.anova(table=table, test=test, scale=sum(
  2688.             object$weights*object$residuals^2)/object$df.residual,
  2689.             df.scale=object$df.residual, n=NROW(x))
  2690.     # return output
  2691.     output <- list(title=title, table=table)
  2692.     class(output) <- "anova.glm"
  2693.     return(output)
  2694. }
  2695. anova.glmlist <- function(object, ..., test=NULL)
  2696. {
  2697.     # find responses for all models and remove
  2698.     # any models with a different response
  2699.     responses <- as.character(lapply(object, function(x) {
  2700.             as.character(x$formula[2])} ))
  2701.     sameresp <- responses==responses[1]
  2702.     if(!all(sameresp)) {
  2703.         object <- object[sameresp]
  2704.         warning(paste("Models with response", deparse(responses[
  2705.             !sameresp]), "removed because response differs from",
  2706.             "model 1"))
  2707.     }
  2708.     # calculate the number of models
  2709.     nmodels <- length(object)
  2710.     if(nmodels==1)    return(anova.glm(object[[1]], ..., test))
  2711.     # extract statistics
  2712.     resdf <- as.numeric(lapply(object, function(x) x$df.residual))
  2713.     resdev <- as.numeric(lapply(object, function(x) x$deviance))
  2714.     # construct table and title
  2715.     table <- cbind(resdf, resdev, c(NA, -diff(resdf)), c(NA, -diff(resdev)))
  2716.     variables <- as.character(lapply(object, function(x) {
  2717.             as.character(x$formula[3])} ))
  2718.     dimnames(table) <- list(variables, c("Resid. Df", "Resid. Dev", "Df",
  2719.                 "Deviance"))
  2720.     title <- paste("Analysis of Deviance Table \n\nResponse: ", responses[1],
  2721.             "\n\n", sep="")
  2722.     # calculate test statistic if needed
  2723.     if(!is.null(test)) {
  2724.         bigmodel <- object[[(order(resdf)[1])]]
  2725.         table <- stat.anova(table=table, test=test, scale=sum(
  2726.             bigmodel$weights * bigmodel$residuals^2)/
  2727.             bigmodel$df.residual, df.scale=min(resdf),
  2728.             n=length(bigmodel$residuals))
  2729.     }
  2730.     # return output
  2731.     output <- list(table=table, title=title)
  2732.     class(output) <- "anova.glm"
  2733.     return(output)
  2734. }
  2735. stat.anova <- function(table, test, scale, df.scale, n)
  2736. {
  2737.     testnum <- match(test, c("Chisq", "F", "Cp"))
  2738.     cnames <- colnames(table)
  2739.     rnames <- rownames(table)
  2740.     if(is.na(testnum))
  2741.         stop(paste("Test \"", test, "\" not recognised", sep=""))
  2742.     if(testnum==1) {
  2743.         chisq <- 1-pchisq(abs(table[, "Deviance"]), abs(table[, "Df"]))
  2744.         table <- cbind(table, chisq)
  2745.         dimnames(table) <- list(rnames, c(cnames, "P(>|Chi|)"))
  2746.     }
  2747.     if(testnum==2) {
  2748.         Fvalue <- abs((table[, "Deviance"]/table[, "Df"])/scale)
  2749.         pvalue <- 1-pf(Fvalue, abs(table[, "Df"]), abs(df.scale))
  2750.         table <- cbind(table, Fvalue, pvalue)
  2751.         dimnames(table) <- list(rnames, c(cnames, "F", "Pr(>F)"))
  2752.     }
  2753.     if(testnum==3) {
  2754.         Cp <- table[, "Resid. Dev"] + 2*scale*(n - table[, "Resid. Df"])
  2755.         table <- cbind(table, Cp)
  2756.         dimnames(table) <- list(rnames, c(cnames, "Cp"))
  2757.     }
  2758.     return(table)
  2759. }
  2760. summary.glm <- function(object, dispersion = NULL,
  2761.     correlation = TRUE, na.action=na.omit)
  2762. {
  2763.     # calculate dispersion if needed
  2764.     if(is.null(dispersion)) {
  2765.         if(any(object$family$family == c("poisson", "binomial")))
  2766.             dispersion <- 1
  2767.         else {
  2768.             if(any(object$weights==0))
  2769.                 warning(paste("observations with zero weight",
  2770.                 "not used for calculating dispersion"))
  2771.             dispersion <- sum(object$weights*object$residuals^2)/
  2772.                     object$df.residual
  2773.         }
  2774.     }
  2775.     # extract x to get column names
  2776.     if(is.null(object$x)) {
  2777.         if(is.null(object$model)) {
  2778.             varlist <- attr(object$terms, "variables")
  2779.             if(is.null(object$data))    
  2780.                 object$data <- sys.frame(sys.parent())
  2781.             object$model <- na.action(model.frame(eval(varlist,
  2782.                 object$data), as.character(varlist[-1]), NULL))
  2783.         }
  2784.         object$x <- model.matrix(object$terms, object$model)
  2785.     }
  2786.     # calculate scaled and unscaled covariance matrix
  2787.     p <- object$rank
  2788.     p1 <- 1:p
  2789.     covmat.unscaled <- chol2inv(object$qr$qr[p1,p1,drop=FALSE])
  2790.     dimnames(covmat.unscaled) <- list(names(object$coefficients)[p1], names(object$coefficients)[p1])
  2791.     covmat <- dispersion*covmat.unscaled
  2792.     dimnames(covmat) <- dimnames(covmat.unscaled)
  2793.     # calculate coef table
  2794.     nas <- is.na(object$coefficients)
  2795.     tvalue <- object$coefficients[p1]/diag(covmat)^0.5
  2796.     pvalue <- 2*(1-pt(abs(tvalue), object$df.residual))
  2797.     coef.table <- cbind(object$coefficients[p1], diag(covmat)^0.5, tvalue, pvalue)
  2798.     dimnames(coef.table) <- list(names(object$coefficients)[p1], c("Value", "Std.error",
  2799.                 "t value", "P(>|t|)"))
  2800.     # return answer
  2801.     ans <- list(
  2802.         call=object$call,
  2803.         terms=object$terms,
  2804.         family=object$family,
  2805.         deviance.resid=residuals(object, type = "deviance"),
  2806.         coefficients=coef.table,
  2807.         dispersion=dispersion,
  2808.         df=c(object$rank, object$df.residual),
  2809.         deviance=object$deviance,
  2810.         df.residual=object$df.residual,
  2811.         null.deviance=object$null.deviance,
  2812.         df.null=object$df.null,
  2813.         iter=object$iter,
  2814.         cov.unscaled=covmat.unscaled,
  2815.         cov.scaled=covmat)
  2816. #        cov.scaled=covmat,
  2817. #        nas=nas)
  2818.     if(correlation) {
  2819.         ans$correlation <- as.matrix(covmat/(outer(diag(covmat),
  2820.             diag(covmat))^0.5))
  2821.     }
  2822.     class(ans) <- "summary.glm"
  2823.     return(ans)
  2824. }
  2825. print.summary.glm <- function (x, digits = max(3, .Options$digits - 3),
  2826.     na.print="", ...)
  2827. {
  2828.         cat("\nCall:\n")
  2829.         cat(paste(deparse(x$call), sep="\n", collapse="\n"), "\n\n", sep="")
  2830.     cat("Deviance Residuals: \n")
  2831.     if(x$df.residual > 5) {
  2832.         x$deviance.resid <- quantile(x$deviance.resid)
  2833.         names(x$deviance.resid) <- c("Min", "1Q", "Median", "3Q", "Max")
  2834.     }
  2835.     print.default(x$deviance.resid, digits=digits, na = "", print.gap = 2)
  2836.     cat("\nCoefficients:\n")
  2837.     print.default(x$coefficients, digits=digits, print.gap = 2)
  2838.     cat(paste("\n(Dispersion parameter for ", x$family$family,
  2839.         " family taken to be ", x$dispersion,
  2840.         ")\n\n    Null deviance: ", x$null.deviance,
  2841.         " on ", x$df.null, " degrees of freedom\n\n",
  2842.         "Residual deviance: ", x$deviance,
  2843.         " on ", x$df.residual, " degrees of freedom\n\n",
  2844.         "Number of Fisher Scoring iterations: ", x$iter,
  2845.         "\n\n", sep=""))
  2846.     correl <- x$correlation
  2847.     if(!is.null(correl)) {
  2848.         p <- dim(correl)[2]
  2849.         if(p > 1) {
  2850.             cat("Correlation of Coefficients:\n")
  2851.             correl[!lower.tri(correl)] <- NA
  2852.             print(correl[-1, -NCOL(correl), drop=FALSE], digits=digits,
  2853.                 na="")
  2854.         }
  2855.         cat("\n")
  2856.     }
  2857.     invisible(x)
  2858. }
  2859. print.anova.glm <- function(x, digits = max(3, .Options$digits - 3),
  2860.     na.print = "", ...)
  2861. {
  2862.     cat("\n", x$title, sep="")
  2863.     print.default(x$table, digits=digits, na = "", print.gap = 2)
  2864.     cat("\n")
  2865. }
  2866. # Generic Functions
  2867. coefficients.glm <- function(object)
  2868.     object$coefficients
  2869. deviance.glm <- function(object)
  2870.     object$deviance
  2871. effects.glm <- function(object)
  2872.     object$effects
  2873. family.glm <- function(object) {
  2874.     family <- get(as.character(object$family$family), mode="function")
  2875.     family()
  2876. }
  2877. fitted.values.glm <- function(object)
  2878.     object$fitted.values
  2879. residuals.glm <- function(object, type="deviance")
  2880. {
  2881.     type <- match(type, c("deviance", "pearson", "working", "response"))
  2882.     y <- object$y
  2883.     mu <- object$fitted.values
  2884.     wts <- object$prior.weights
  2885.     switch(type,
  2886.         deviance={
  2887.             dev.resids <- object$family$dev.resids
  2888.             ifelse(y>mu, dev.resids(y, mu, wts)^0.5, -(dev.resids(
  2889.                 y, mu, wts)^0.5))
  2890.         },
  2891.         pearson=object$residuals * object$weights^0.5,
  2892.         working=object$residuals,
  2893.         response=y - mu
  2894.         )
  2895. }
  2896. grep <-
  2897. function(pattern, x, ignore.case=FALSE, extended=TRUE, value=FALSE)
  2898. {
  2899.     .Internal(grep(pattern, x, ignore.case, extended, value))
  2900. }
  2901. sub <-
  2902. function(pattern, replacement, x, ignore.case=FALSE, extended=TRUE)
  2903. {
  2904.     .Internal(sub(pattern, replacement, x, ignore.case, extended))
  2905. }
  2906. gsub <-
  2907. function(pattern, replacement, x, ignore.case=FALSE, extended=TRUE)
  2908. {
  2909.     .Internal(gsub(pattern, replacement, x, ignore.case, extended))
  2910. }
  2911. "grid" <-
  2912. function (nx=3, ny=3, col="lightgray", lty="dotted") 
  2913. {
  2914.     lims <- par("usr")
  2915.     if (nx > 1) {
  2916.         coord <- seq(lims[1], lims[2], len = nx + 2)[c(-1, -(nx + 2))]
  2917.         abline(v = coord, col = col, lty = lty)
  2918.     }
  2919.     if (ny > 1) {
  2920.         coord <- seq(lims[3], lims[4], len = ny + 2)[c(-1, -(ny + 2))]
  2921.         abline(h = coord, col = col, lty = lty)
  2922.     }
  2923. }
  2924. "help" <-
  2925. function (topic, data, library)
  2926. {
  2927.     if(!missing(topic)) {
  2928.         topic <- substitute(topic)
  2929.         if (is.character(topic) || is.name(topic)) {
  2930.             if (!is.character(topic)) 
  2931.                 topic <- deparse(topic)
  2932.             if (!is.na(match(topic, c("+", "-", "*", "/", "^", "%%")))) 
  2933.                 topic <- "Arithmetic"
  2934.             else if (!is.na(match(topic, c("<", ">", "<=", ">=", "==", "!=")))) 
  2935.                 topic <- "Comparison"
  2936.             else if (!is.na(match(topic, c("&", "&&", "|", "||", "!")))) 
  2937.                 topic <- "Logic"
  2938.             else if (!is.na(match(topic, c("[", "[[", "$"))))
  2939.                 topic <- "Extract"
  2940.             system(paste("$RHOME/cmd/help", topic,
  2941.                 paste(.Libraries, collapse = " "), "base"))
  2942.         }
  2943.         else {
  2944.             topic <- as.character(topic)
  2945.             if (topic[1] == "data") {
  2946.                 file <- system.file("data", paste(topic[2], ".doc", sep = ""))
  2947.                 if (file == "") 
  2948.                     stop(paste("no documentation for dataset", topic[2]))
  2949.                 else system(paste("$RHOME/cmd/pager", file))
  2950.             }
  2951.             else if (topic[1] == "library") {
  2952.                 file <- system.file("help", paste(topic[2], "/INDEX", sep = ""))
  2953.                 if (file == "") 
  2954.                     stop(paste("no documentation for dataset", topic[2]))
  2955.                 else system(paste("$RHOME/cmd/pager", file))
  2956.             }
  2957.             else stop("unimplemented help feature")
  2958.         }
  2959.     }
  2960.     else if(!missing(data)) {
  2961.         topic <- as.character(substitute(data))
  2962.         file <- system.file("data", paste(topic, ".doc", sep = ""))
  2963.         if (file == "") 
  2964.             stop(paste("no documentation for dataset", topic))
  2965.         else system(paste("$RHOME/cmd/pager", file))
  2966.     }
  2967.     else if(!missing(library)) {
  2968.         topic <- as.character(substitute(library))
  2969.         file <- system.file("help", paste(topic, "/INDEX", sep = ""))
  2970.         if (file == "") 
  2971.             stop(paste("no documentation for library", topic))
  2972.         else system(paste("$RHOME/cmd/pager", file))
  2973.     }
  2974.     else system("$RHOME/cmd/help help base")
  2975. }
  2976. # help.start <- function (gui = "irrelevant", browser="netscape -mono") 
  2977. # {
  2978. #         system(paste(browser,"$RHOME/html/index.html&"))
  2979. # }
  2980. help.start <-
  2981. function(gui = "irrelevant", browser="netscape")
  2982. {
  2983.     file <- "$RHOME/html/index.html"
  2984.     system(paste(browser, " -remote \"openURL(", file,
  2985.         ")\" 2>/dev/null || ", browser, " ", file, " &", sep = ""))
  2986. }
  2987. "hist" <-
  2988. function (x, breaks, freq = TRUE, col = NULL, border = par("fg"),
  2989.     main = paste("Histogram of" , deparse(substitute(x))),
  2990.     xlim = range(breaks), ylim = range(counts, 0),
  2991.     xlab = deparse(substitute(x)), ylab, ...)
  2992. {
  2993.     if (!is.numeric(x)) 
  2994.         stop("hist: x must be numeric")
  2995.     if (missing(breaks)) {
  2996.         breaks <- range(x)
  2997.         breaks <- pretty(breaks + c(0, diff(breaks)/1000),
  2998.                     1 + log2(length(x)))
  2999.     }
  3000.     else if (length(breaks) == 1) {
  3001.         if (is.na(breaks) | breaks < 2) 
  3002.             stop("invalid number of breaks")
  3003.         nbreaks <- breaks
  3004.         breaks <- range(x)
  3005.         breaks <- pretty(breaks + c(0, diff(breaks)/1000), nbreaks)
  3006.     }
  3007.     breaks <- sort(breaks)
  3008.     counts <- .C("bincount", 
  3009.         as.double(x), 
  3010.         length(x), 
  3011.         as.double(breaks), 
  3012.         length(breaks), 
  3013.         counts = integer(length(breaks) - 1), 
  3014.         TRUE
  3015.     )[[5]]
  3016.     if (any(counts < 0)) 
  3017.         browser()
  3018.     if (!freq) {
  3019.         counts <- counts/(sum(!is.na(x)) * diff(breaks))
  3020.         if (missing(ylab)) 
  3021.             ylab <- "Relative Frequency"
  3022.     }
  3023.     else if (missing(ylab)) 
  3024.         ylab <- "Frequency"
  3025.     plot.new()
  3026.     plot.window(xlim, ylim, "")
  3027.     title(main = main, xlab = xlab, ylab = ylab, ...)
  3028.     axis(1, ...)
  3029.     axis(2, ...)
  3030.     rect(breaks[-length(breaks)], 0, breaks[-1], counts,
  3031.         col = col, border = border)
  3032.     invisible(NULL)
  3033. }
  3034. print.htest<-function(x, digits = 4, quote = T, prefix = "")
  3035. {
  3036.         cat("\n\t", x$method, "\n\n")
  3037.         cat("data: ", x$data.name, "\n")
  3038.         if(!is.null(x$statistic))
  3039.                 cat(names(x$statistic), " = ", format(round(x$statistic, 4)), 
  3040.                         ", ", sep = "")
  3041.     if(!is.null (x$parameter))    
  3042.         cat(paste(names(x$parameter), " = ", format(round(x$parameter,
  3043.             3)), ",", sep = ""), "")
  3044.         cat("p-value =", format(round(x$p.value, 4)), "\n")
  3045.         if(!is.null(x$alternative)) {
  3046.                 if(!is.null(x$null.value)) {
  3047.                         if(length(x$null.value) == 1) {
  3048.                                 if (x$alternative == "two.sided" )
  3049.                     alt.char <- "not equal to"
  3050.                 else if( x$alternative == "less" )
  3051.                     alt.char <- "less than"
  3052.                 else if( x$alternative == "greater" )
  3053.                                       alt.char <- "greater than"
  3054.                                 cat("alternative hypothesis:", "true", names(x$
  3055.                                   null.value), "is", alt.char, x$null.value, 
  3056.                                   "\n")
  3057.                         }
  3058.                         else {
  3059.                                 cat("alternative hypothesis:", x$alternative, 
  3060.                                   "\n")
  3061.                                 cat("null values:\n")
  3062.                                 print(x$null.value)
  3063.                         }
  3064.                 }
  3065.                 else cat("alternative hypothesis:", x$alternative, "\n")
  3066.         }
  3067.         if(!is.null(x$conf.int)) {
  3068.                 cat(format(100 * attr(x$conf.int, "conf.level")), 
  3069.                         "percent confidence interval:\n", format(c(x$conf.int[1
  3070.                         ], x$conf.int[2])), "\n")
  3071.         }
  3072.         if(!is.null(x$estimate)) {
  3073.                 cat("sample estimates:\n")
  3074.                 print(x$estimate)
  3075.         }
  3076.         cat("\n")
  3077.         invisible(x)
  3078. }
  3079. identify <- function(x, y=NULL, text=as.character(seq(x)), pos=FALSE, ...) {
  3080.     opar <- par(list(...))
  3081.     on.exit(par(opar))
  3082.     xy <- xy.coords(x, y)
  3083.     z <- .Internal(identify(xy$x,xy$y,as.character(text)))
  3084.     i <- seq(z[[1]])[z[[1]]]
  3085.     p <- z[[2]][z[[1]]]
  3086.     if(pos) list(ind=i,pos=p) else i
  3087. }
  3088. ifelse <- 
  3089. function (test, yes, no) 
  3090. {
  3091.         ans <- test
  3092.         test <- as.logical(test)
  3093.         nas <- is.na(test)
  3094.         ans[test] <- rep(yes, length = length(ans))[test]
  3095.         ans[!test] <- rep(no, length = length(ans))[!test]
  3096.         ans[nas] <- NA
  3097.         ans
  3098. }
  3099. "image" <-      
  3100. function (x=seq(0,1,len=nrow(z)), y=seq(0,1,len=ncol(z)), z,
  3101.     zlim=range(z, na.rm=TRUE), col=heat.colors(12), ...)
  3102. {
  3103.     plot(0, 0, xlim=range(x,na.rm=TRUE), ylim=range(y,na.rm=TRUE),
  3104.         type="n", xaxs = "i", yaxs = "i", xlab="", ylab="", ...)
  3105.     .Internal(image(
  3106.             as.double(x),
  3107.             as.double(y),
  3108.             as.double(z),
  3109.             as.double(zlim),
  3110.             col))
  3111. }
  3112. "IQR" <-
  3113. function (x) 
  3114. as.vector(diff(quantile(as.numeric(x), c(0.25, 0.75))))
  3115. is.vector <- function(x, mode="any") .Internal(is.vector(x,mode))
  3116. is.finite <- function(x) !is.na(x)
  3117. is.symbol <- function(x) typeof(x)=="symbol"
  3118. lapply <- function(x, FUN, ...)
  3119. {
  3120.     if(is.character(FUN))
  3121.         FUN <- get(FUN,mode="function")
  3122.     if(mode(FUN) != "function")
  3123.         stop(paste("\"",FUN,"\" is not a function",sep=" "))
  3124.     if(!is.list(x))
  3125.         stop("lapply can only be used for lists")
  3126.     rval <- vector("list",length(x))
  3127.     for(i in seq(along=x))
  3128.         rval[i] <- list(FUN(x[[i]],...))
  3129.     names(rval) <- names(x) # keep 'names' !
  3130.     return(rval)
  3131. }
  3132. legend <-
  3133. function(x, y, legend, fill, col="black", lty, pch, bty="o", bg=par("bg"),
  3134.     xjust=0, yjust=1, ...)
  3135. {
  3136.     xchar <- xinch(par("cin")[1])
  3137.     ychar <- yinch(par("cin")[2]) * 1.2
  3138.     xbox <- xinch(par("cin")[2] * 0.8)
  3139.     ybox <- yinch(par("cin")[2] * 0.8)
  3140.     yline <- 2*xchar
  3141.     w <- 2 * xchar + max(strwidth(legend))
  3142.     h <- (length(legend)+1)*ychar
  3143.     if(missing(y)) {
  3144.         if(is.list(x)) {
  3145.             y <- x$y
  3146.             x <- x$x
  3147.         }
  3148.     }
  3149.     if(!is.numeric(x) || !is.numeric(y))
  3150.         stop("non-numeric coordinates")
  3151.     if(length(x) <= 0 || length(x) != length(y))
  3152.         stop("differing coordinate lengths")
  3153.     if(length(x) != 1) {
  3154.         x <- mean(x)
  3155.         y <- mean(y)
  3156.         xjust <- 0.5
  3157.         yjust <- 0.5
  3158.     }
  3159.     if(!missing(fill)) {
  3160.         w <- w + xchar + xbox
  3161.     }
  3162.     if(!missing(pch)) {
  3163.         if(is.character(pch) && nchar(pch) > 1) {
  3164.             np <- nchar(pch)
  3165.             pch <- substr(rep(pch[1], np), 1:np, 1:np)
  3166.         }
  3167.         w <- w + 1.5 * xchar
  3168.     }
  3169.     if(!missing(lty))
  3170.         w <- w + 3 * xchar
  3171.     x <- x - xjust * w
  3172.     y <- y + (1 - yjust) * h
  3173.     xt <- rep(x, length(legend)) + xchar
  3174.     yt <- y - (1:length(legend)) * ychar
  3175.     if(bty != "n")
  3176.         rect(x, y, x+w, y-h, col=bg)
  3177.     x <- x + xchar
  3178.     if(!missing(fill)) {
  3179.         rect(xt, yt - 0.5 * ybox,
  3180.             xt + xbox, yt + 0.5 * ybox, col=fill)
  3181.         xt <- xt + xbox + xchar
  3182.     }
  3183.     if(!missing(pch)) {
  3184.         points(xt + 0.25 * xchar, yt, pch, col=col)
  3185.         xt <- xt + 1.5 * xchar
  3186.     }
  3187.     if(!missing(lty)) {
  3188.         segments(xt, yt, xt + 2 * xchar, yt, lty=lty, col=col)
  3189.         xt <- xt + 3 * xchar
  3190.     }
  3191.     text(xt, yt, text=legend, adj=c(0, 0.35))
  3192. }
  3193. library <- function(name)
  3194. {
  3195.     if (!exists(".Libraries", inherits=TRUE))
  3196.         assign(".Libraries", character(0), NULL)
  3197.     if(missing(name)) {
  3198.         cat("NAME\tDESCRIPTION\n")
  3199.         system(paste("cat", system.file("help","LibIndex")))
  3200.     }
  3201.     else {
  3202.         name <- substitute(name)
  3203.         if (!is.character(name)) 
  3204.             name <- deparse(name)
  3205.         if(is.na(match(name, .Libraries))) {
  3206.             file <- system.file("library", name)
  3207.             if(file == "") stop(paste("there is no library called", name))
  3208.             sys.source(file)
  3209.             assign(".Libraries", c(name, .Libraries), NULL)
  3210.         }
  3211.         invisible(.Libraries)
  3212.     }
  3213. }
  3214. library.dynam <- function(name)
  3215. {
  3216.     if (!exists(".Dyn.libs"))
  3217.         assign(".Dyn.libs", character(0), NULL)
  3218.     if(is.na(match(name, .Dyn.libs))) {
  3219.         .Internal(dyn.load(system.file("lib", name)))
  3220.         assign(".Dyn.libs", c(.Dyn.libs, name), NULL)
  3221.     }
  3222.     invisible(.Dyn.libs)
  3223. }
  3224. license <- function() {
  3225. cat("\nThis software is distributed under the terms of the GNU GENERAL\n")
  3226. cat("PUBLIC LICENSE Version 2, June 1991.  The terms of this license\n")
  3227. cat("are in a file called COPYING which you should have received with\n")
  3228. cat("this software.\n")
  3229. cat("\n")
  3230. cat("If you have not received a copy of this file, you can obtain one\n")
  3231. cat("by writing to:\n")
  3232. cat("\n")
  3233. cat("    The Free Software Foundation, Inc.\n")
  3234. cat("    675 Mass Ave, Cambridge, MA 02139, USA\n")
  3235. cat("\n")
  3236. cat("``Share and Enjoy.''\n\n")
  3237. }
  3238. lines <- function(x, ...)
  3239. UseMethod("lines")
  3240. lines.default <- function(x, y=NULL, type="l", col=par("col"), ...) {
  3241.     plot.xy(xy.coords(x, y), type=type, col=col, ...)
  3242. }
  3243. lm <- function(formula, data=NULL, subset=NULL, weights=NULL,
  3244.     na.action=na.fail, singular.ok=TRUE)
  3245. {
  3246.     mt <- terms(formula)
  3247.     if(is.null(data)) data <- sys.frame(sys.parent())
  3248.     mf <- match.call()
  3249.     mf$singular.ok <- NULL
  3250.     mf$use.data <- TRUE
  3251.     mf[[1]] <- as.name("model.frame")
  3252.     mf <- eval(mf, sys.frame(sys.parent()))
  3253.     x <- model.matrix(mt, mf);
  3254.     y <- model.response(mf, "numeric")
  3255.     w <- model.weights(mf)
  3256.     if(is.null(w)) {
  3257.         z <- lm.fit(x,y)
  3258.     }
  3259.     else {
  3260.         z <- lm.w.fit(x,y,w)
  3261.     }
  3262.     z$call <- match.call()
  3263.     z$terms <- mt
  3264.     z$model.frame <- mf
  3265.     class(z) <- if(is.matrix(y)) c("mlm","lm") else "lm"
  3266.     z
  3267. }
  3268. lm.fit <- function(x, y)
  3269. {
  3270.     n <- nrow(x)
  3271.     p <- ncol(x)
  3272.     ny <- NCOL(y)
  3273.     if(NROW(y) != n) stop("incompatible dimensions")
  3274.     z <- .Fortran("dqrls",
  3275.         qr=x,
  3276.         n=n,
  3277.         p=p,
  3278.         y=y,
  3279.         ny=ny,
  3280.         tol=1e-7,
  3281.         coefficients=mat.or.vec(p,ny),
  3282.         residuals=y,
  3283.         effects=y,
  3284.         rank=integer(1),
  3285.         pivot=as.integer(1:p),
  3286.         qraux=double(p),
  3287.         work=double(2*p))
  3288.     coef <- z$coefficients
  3289.     pivot <- z$pivot
  3290.     r1 <- 1:z$rank
  3291.     if(ny > 1) {
  3292.         coef[-r1,] <- NA
  3293.         coef[pivot,] <- coef
  3294.         dimnames(coef) <- list(dimnames(x)[[2]],dimnames(y)[[2]])
  3295.         dimnames(z$effects)[1] <- list(NULL)
  3296.     }
  3297.     else {
  3298.         coef[-r1] <- NA
  3299.         coef[pivot] <- coef
  3300.         names(coef) <- dimnames(x)[[2]]
  3301.         names(z$effects) <- NULL
  3302.     }
  3303.     z$coefficients <- coef
  3304.     c(z[c("coefficients","residuals","effects","rank")],
  3305.         list(fitted.values=y-z$residuals,
  3306.             assign=attr(x,"assign"),
  3307.             qr=z[c("qr","qraux","pivot","tol","rank")],
  3308.             df.residual=n-z$rank))
  3309. }
  3310. lm.w.fit <- function(x, y, w)
  3311. {
  3312.     n <- nrow(x)
  3313.     p <- ncol(x)
  3314.     ny <- NCOL(y)
  3315.     if(NROW(y) != n | length(w) != n)
  3316.         stop("incompatible dimensions")
  3317.     if(any(w < 0 | is.na(w)))
  3318.         stop("missing or negative weights not allowed")
  3319.     zero.weights <- FALSE
  3320.     if(any(w == 0)) {
  3321.         zero.weights <- TRUE
  3322.         save.r <- y
  3323.         save.f <- y
  3324.         save.w <- w
  3325.         ok <- w != 0
  3326.         nok <- !ok
  3327.         w <- w[ok]
  3328.         x0 <- x[!ok,]
  3329.         x <- x[ok,]
  3330.         y0 <- if(ny>1) y[!ok,,drop=FALSE] else y[!ok]
  3331.         y <- if(ny>1) y[ok,,drop=FALSE] else y[ok]
  3332.     }
  3333.     n <- nrow(x)
  3334.     p <- ncol(x)
  3335.     wts <- w^0.5
  3336.     z <- .Fortran("dqrls",
  3337.         qr=x*wts,
  3338.         n=n,
  3339.         p=p,
  3340.         y=y*wts,
  3341.         ny=ny,
  3342.         tol=1e-7,
  3343.         coefficients=mat.or.vec(p,ny),
  3344.         residuals=y,
  3345.         effects=mat.or.vec(n,ny),
  3346.         rank=integer(1),
  3347.         pivot=as.integer(1:p),
  3348.         qraux=double(p),
  3349.         work=double(2*p))
  3350.     coef <- z$coefficients
  3351.     pivot <- z$pivot
  3352.     r1 <- 1:z$rank
  3353.     if(ny > 1) {
  3354.         coef[-r1,] <- NA
  3355.         coef[pivot,] <- coef
  3356.         dimnames(coef) <- list(dimnames(x)[[2]],dimnames(y)[[2]])
  3357.         dimnames(z$residuals) <- dimnames(y)
  3358.         dimnames(z$effects)[[2]] <- dimnames(y)[[2]]
  3359.     }
  3360.     else {
  3361.         coef[-r1] <- NA
  3362.         coef[pivot] <- coef
  3363.         names(coef) <- dimnames(x)[[2]]
  3364.         names(z$residuals) <- names(y)
  3365.     }
  3366.     z$coefficients <- coef
  3367.     z$residuals <- z$residuals/wts
  3368.     z$fitted.values <- (y - z$residuals)
  3369.     z$weights <- w
  3370.     if(zero.weights) {
  3371.         coef[is.na(coef)] <- 0
  3372.         f0 <- x0 %*% coef
  3373.         if(ny > 1) {
  3374.             save.r[ok,] <- z$residuals
  3375.             save.r[ok,] <- y0 - f0
  3376.             save.f[ok,] <- fitted.values
  3377.             save.f[nok,] <- f0
  3378.         }
  3379.         else {
  3380.             save.r[ok] <- z$residuals
  3381.             save.r[ok] <- y0 - f0
  3382.             save.f[ok] <- fitted.values
  3383.             save.f[nok] <- f0
  3384.         }
  3385.         z$residuals <- save.r
  3386.         z$fitted.values <- save.f
  3387.         z$weights <- save.w
  3388.     }
  3389.     else {
  3390.         if(ny > 1) {
  3391.             dimnames(z$residuals) <- dimnames(y)
  3392.             dimnames(z$fitted.values) <- dimnames(y)
  3393.         }
  3394.         else {
  3395.             names(z$residuals) <- names(y)
  3396.             names(z$fitted.values) <- names(y)
  3397.         }
  3398.     }
  3399.     c(z[c("coefficients","residuals","fitted.values",
  3400.         "effects","weights","rank")], list(
  3401.             assign=attr(x,"assign"),
  3402.             qr=z[c("qr","qraux","pivot","tol","rank")],
  3403.             df.residual=n-z$rank))
  3404. }
  3405. update.lm <-
  3406. function(lm.obj, formula, data, weights, subset, na.action)
  3407. {
  3408.     call <- lm.obj$call
  3409.     if(!missing(formula))
  3410.         call$formula <- update.formula(call$formula, formula)
  3411.     if(!missing(data)) call$data <- substitute(data)
  3412.     if(!missing(subset)) call$subset <- substitute(subset)
  3413.     if(!missing(na.action)) call$na.action <- substitute(na.action)
  3414.     eval(call, sys.frame(sys.parent()))
  3415. }
  3416. residuals.lm <- function(z) z$residuals
  3417. fitted.values.lm <- function(z) z$fitted.values
  3418. coefficients.lm <- function(z) z$coefficients
  3419. weights.lm <- function(z) z$weights
  3420. df.residual.lm <- function(z) z$df.residual
  3421. deviance.lm <- function(z) sum((z$residuals)^2)
  3422. summary.lm <- function(z, correlation=FALSE)
  3423. {
  3424.     n <- NROW(z$qr$qr)
  3425.     p <- z$rank
  3426.     p1 <- 1:p
  3427.     r <- resid(z)
  3428.     f <- fitted(z)
  3429.     w <- weights(z)
  3430.     if (is.null(z$terms)) {
  3431.         stop("invalid 'lm' object:  no terms component")
  3432.     } else {
  3433.         if (attr(z$terms,"intercept")) {
  3434.             if(is.null(w)) {
  3435.                 rss <- sum(r^2)
  3436.                 mss <- sum((f-mean(f))^2)
  3437.             } else {
  3438.                 wok <- (w!=0)
  3439.                 u <- (sqrt(w)/sqrt(sum(w)))[wok]
  3440.                 r <- sqrt(w)*r[wok]
  3441.                 f <- sqrt(w)*f[wok]
  3442.                 rss <- sum(r^2)
  3443.                 mss <- sum((f - sum(f*u)*u)^2)
  3444.             }
  3445.         } else { #- no intercept
  3446.             rss <- sum(r^2)
  3447.             mss <- sum(f^2)
  3448.         }
  3449.     }
  3450.     resvar <- rss/(n-p)
  3451.     R <- chol2inv(z$qr$qr[p1,p1,drop=FALSE])
  3452.     se <- sqrt(diag(R)*resvar)
  3453.     est <- z$coefficients[z$qr$pivot[p1]]
  3454.     tval <- est/se
  3455.     ans <- z[c("call","terms")]
  3456.     ans$residuals <- r
  3457.     ans$coefficients <- cbind(est, se, tval, 2*(1-pt(abs(tval),n-p)))
  3458.     dimnames(ans$coefficients) <- 
  3459.         list(names(z$coefficients)[z$qr$pivot[p1]],
  3460.             c("Estimate", "Std.Error","t Value", "Pr(>|t|)"))
  3461.     ans$sigma <- sqrt(resvar)
  3462.     ans$df <- c(p, n-p, NCOL(z$qr$qr))
  3463.     if(p != attr(z$terms,"intercept")) {
  3464.           df.int <- if(attr(z$terms,"intercept")) 1 else 0
  3465.         ans$r.squared <- mss/(mss+rss)
  3466.         ans$adj.r.squared <- 1-(1-ans$r.squared)*    
  3467.           ((n - df.int) / (n - p))    #0.14 :    (n/(n-p))
  3468.         ans$fstatistic <- c((mss/(p-df.int))/(rss/(n-p)),p-df.int,n-p)
  3469.          #0.14: ans$fstatistic <- c((mss/(p-1))/(rss/(n-p)),p-1,n-p)
  3470.         names(ans$fstatistic) <- c("value","numdf","dendf")
  3471.     }
  3472.     ans$cov.unscaled <- R
  3473.     dimnames(ans$cov.unscaled) <- dimnames(ans$coefficients)[c(1,1)]
  3474.     if(correlation) {
  3475.         ans$correlation <- (R*resvar)/outer(se,se)
  3476.         dimnames(ans$correlation) <- dimnames(ans$cov.unscaled)
  3477.     }
  3478.     class(ans) <- "summary.lm"
  3479.     ans
  3480. }
  3481. print.lm <- function(x, digits = max(3, .Options$digits - 3), ...)
  3482. {
  3483.     cat("\nCall:\n",deparse(x$call),"\n\n",sep="")
  3484.     cat("Coefficients:\n")
  3485.     print(coef(x))
  3486.     cat("\n")
  3487. }
  3488. print.summary.lm <- function(x, digits = max(3, .Options$digits - 3), ...)
  3489. {
  3490.     cat("\nCall:\n")
  3491.         cat(paste(deparse(x$call), sep="\n", collapse="\n"), "\n\n", sep="")
  3492.     resid <- x$residuals
  3493.     df <- x$df
  3494.     rdf <- df[2]
  3495.     if(rdf > 5) {
  3496.         cat("Residuals:\n")
  3497.         if(length(dim(resid)) == 2) {
  3498.             rq <- apply(t(resid), 1, quantile)
  3499.             dimnames(rq) <- list(c("Min", "1Q", "Median", "3Q", "Max"),
  3500.                 dimnames(resid)[[2]])
  3501.         }
  3502.         else {
  3503.             rq <- quantile(resid)
  3504.             names(rq) <- c("Min", "1Q", "Median", "3Q", "Max")
  3505.         }
  3506.         print(rq, digits = digits, ...)
  3507.     }
  3508.     else if(rdf > 0) {
  3509.         cat("Residuals:\n")
  3510.         print(resid, digits = digits, ...)
  3511.     }
  3512.     if(nsingular <- df[3] - df[1])
  3513.         cat("\nCoefficients: (", nsingular,
  3514.             " not defined because of singularities)\n", sep = "")
  3515.     else cat("\nCoefficients:\n")
  3516.     print(x$coefficients, digits=digits, quote = FALSE, ...)
  3517.     cat("\nResidual standard error:", format(signif(x$sigma, digits)), "on",
  3518.         rdf, "degrees of freedom\n")
  3519.     if(!is.null(x$fstatistic)) {
  3520.         cat("Multiple R-Squared:",
  3521.             format(signif(x$r.squared, digits)))
  3522.         cat(",  Adjusted R-squared:",
  3523.             format(signif(x$adj.r.squared, digits)),"\n")
  3524.         cat("F-statistic:", format(signif(x$fstatistic[1], digits)),
  3525.             "on", x$fstatistic[2], "and", x$fstatistic[3],
  3526.             "degrees of freedom")
  3527.         cat(",  p-value:", format(signif(1 - pf(x$fstatistic[1],
  3528.             x$fstatistic[2], x$fstatistic[3]), digits)), "\n")
  3529.     }
  3530.     correl <- x$correlation
  3531.     if(!is.null(correl)) {
  3532.         p <- dim(correl)[2]
  3533.         if(p > 1) {
  3534.             cat("\nCorrelation of Coefficients:\n")
  3535.             correl[!lower.tri(correl)] <- NA
  3536.             print(correl[-1,-NCOL(correl)], digits=digits, na="")
  3537.         }
  3538.     }
  3539.     cat("\n")
  3540.     invisible(x)
  3541. }
  3542. anova.lm <- function(object, ...)
  3543. {
  3544.     if(length(list(object, ...)) > 1)
  3545.         return(anovalist.lm(object, ...))
  3546.     w <- weights(object)
  3547.     if(is.null(w)) ssr <- sum(resid(object)^2)
  3548.     else ssr <- sum(w*resid(object)^2)
  3549.     comp <- object$effects[1:object$rank]
  3550.     asgn <- object$assign[object$qr$pivot][1:object$rank]
  3551.     dfr <- df.residual(object)
  3552.     ss <- c(as.numeric(lapply(split(comp^2,asgn),sum)),ssr)
  3553.     df <- c(as.numeric(lapply(split(asgn,asgn),length)), dfr)
  3554.     if(attr(object$terms,"intercept")) {
  3555.         ss <- ss[-1]
  3556.         df <- df[-1]
  3557.     }
  3558.     ms <- ss/df
  3559.     f <- ms/(ssr/dfr)
  3560.     p <- 1-pf(f,df,dfr)
  3561.     table <- cbind(df,ss,ms,f,p)
  3562.     table[length(p),4:5] <- NA
  3563.     dimnames(table) <- list(c(attr(object$terms,"term.labels"),
  3564.         "Residual"), c("Df","Sum Sq", "Mean Sq", "F", "Pr(>F)"))
  3565.     result <- list(table=table, title="Analysis of Variance Table")
  3566.     class(result) <- "tabular"
  3567.     result
  3568. }
  3569. "anovalist.lm" <-
  3570. function (object, ..., test = NULL) 
  3571. {
  3572.     objects <- list(object, ...)
  3573.     responses <- as.character(lapply(objects, function(x) {
  3574.         as.character(x$terms[[2]])
  3575.     }))
  3576.     sameresp <- responses == responses[1]
  3577.     if (!all(sameresp)) {
  3578.         objects <- objects[sameresp]
  3579.         warning(paste("Models with response",
  3580.             deparse(responses[!sameresp]), 
  3581.             "removed because response differs from", "model 1"))
  3582.     }
  3583.     # calculate the number of models
  3584.     nmodels <- length(objects)
  3585.     if (nmodels == 1) 
  3586.         return(anova.lm(object))
  3587.     models <- as.character(lapply(objects, function(x) x$terms))
  3588.     # extract statistics
  3589.     df.r <- unlist(lapply(objects, df.residual))
  3590.     ss.r <- unlist(lapply(objects, deviance))
  3591.     df <- c(NA, -diff(df.r))
  3592.     ss <- c(NA, -diff(ss.r))
  3593.     ms <- ss/df
  3594.     f <- p <- rep(NA,nmodels)
  3595.     for(i in 2:nmodels) {
  3596.         if(df[i] > 0) {
  3597.             f[i] <- ms[i]/(ss.r[i]/df.r[i])
  3598.             p[i] <- 1 - pf(f[i], df[i], df.r[i])
  3599.         }
  3600.         else {
  3601.             f[i] <- ms[i]/(ss.r[i-1]/df.r[i-1])
  3602.             p[i] <- 1 - pf(f[i], -df[i], df.r[i-1])
  3603.         }
  3604.     }
  3605.     table <- cbind(df.r,ss.r,df,ss,f,p)
  3606.     dimnames(table) <- list(1:nmodels, c("Res.Df", "Res.Sum-Sq", "Df",
  3607.         "Sum-Sq", "F", "Pr(>F)"))
  3608.     # construct table and title
  3609.     title <- "Analysis of Variance Table"
  3610.     topnote <- paste("Model ", format(1:nmodels),": ",
  3611.                 models, sep="", collapse="\n")
  3612.     # calculate test statistic if needed
  3613.     output <- list(table = table, title = title, topnote=topnote)
  3614.     class(output) <- "tabular"
  3615.     return(output)
  3616. }
  3617. print.anova.lm <- function(x, digits = max(3, .Options$digits - 3), ...)
  3618. {
  3619.     class(x) <- NULL
  3620.     cat("\nAnalysis of Variance:\n\n")
  3621.     print.default(round(x, digits), na="", print.gap=2)
  3622.     cat("\n")
  3623. }
  3624. effects.lm <- function(z, term) {
  3625.     term <- deparse(substitute(term))
  3626.     k <- match(term,attr(z$terms,"term.labels"))
  3627.     if(is.na(k)) stop("effect not found")
  3628.     pattern <- attr(z$terms,"factors")[,k]
  3629.     factors <- as.logical(lapply(z$model.frame,is.factor))
  3630.     y <- model.response(z$model.frame,"numeric")
  3631.     k <- range(seq(length(z$assign))[z$assign==k])
  3632.     yhat0 <- if(k[1] > 1) qr.fitted(z$qr,y,k[1]-1) else 0
  3633.     yhat1 <- qr.fitted(z$qr,y,k[2])
  3634.     effects <- yhat1-yhat0
  3635.     tapply(effects,z$model.frame[factors & pattern!=0],mean,na.rm=TRUE)
  3636. }
  3637. lm.influence <-
  3638. function(z)
  3639. {
  3640.     n <- as.integer(nrow(z$qr$qr))
  3641.     k <- as.integer(z$qr$rank)
  3642.     .Fortran("lminfl",
  3643.         z$qr$qr, n, n, k,
  3644.         z$qr$qraux,
  3645.         z$coefficients,
  3646.         z$residuals,
  3647.         hat=double(n),
  3648.         coef=matrix(0,nr=n,nc=k),
  3649.         sigma=double(n),
  3650.         DUP=FALSE)[c("hat", "coef", "sigma")]
  3651. }
  3652. rstudent <-
  3653. function(z)
  3654. {
  3655.     infl <- lm.influence(z)
  3656.     residuals(z)/(infl$sigma*sqrt(1-infl$hat))
  3657. }
  3658. dfbetas <-
  3659. function(z)
  3660. {
  3661.     infl <- lm.influence(z)
  3662.     xxi <- chol2inv(z$qr$qr,z$qr$rank)
  3663.     d <- infl$coef/(outer(infl$sigma, sqrt(diag(xxi))))
  3664.     dn <- dimnames(z$qr$qr)
  3665.     dn[[2]] <- dn[[2]][1:z$qr$rank]
  3666.     dimnames(d) <- dn
  3667.     d
  3668. }
  3669. dffits <-
  3670. function(z)
  3671. {
  3672.     infl <- lm.influence(z)
  3673.     sqrt(infl$hat)*residuals(z)/(infl$sigma*(1-infl$hat))
  3674. }
  3675. covratio <-
  3676. function(z)
  3677. {
  3678.     infl <- lm.influence(z)
  3679.     n <- nrow(z$qr$qr)
  3680.     p <- z$rank
  3681.     e.star <- residuals(z)/(infl$sigma*sqrt(1-infl$hat))
  3682.     1/((((n - p - 1)+e.star^2)/(n - p))^p*(1-infl$hat))
  3683. }
  3684. save <- function(..., list = character(0), file = "", ascii = FALSE) {
  3685.     names <- as.character( substitute( list(...)))[-1]
  3686.     list<- c(list, names)
  3687.     invisible(.Internal(save( list, file, ascii)))
  3688. }
  3689. load <- function(file) 
  3690.     .Internal(load(file))
  3691. locator <- function(n=1) {
  3692.     z <- .Internal(locator(n))
  3693.     x <- z[[1]]
  3694.     y <- z[[2]]
  3695.     n <- z[[3]]
  3696.     if(n==0) NULL else list(x=x[1:n],y=y[1:n])
  3697. }
  3698. log10 <- function(x) log(x,10)
  3699. log2 <- function(x) log(x,2)
  3700. lower.tri <- function(x, diag = FALSE)
  3701. {
  3702.     x <- as.matrix(x)
  3703.         if(diag) row(x) >= col(x)
  3704.         else row(x) > col(x)
  3705. }
  3706. lowess <- function(x, y=NULL, f=2/3, iter=3, delta=.01*diff(range(xy$x[o]))) {
  3707.     xy <- xy.coords(x,y)
  3708.     if(length(xy$x) != length(xy$y)) stop("x and y lengths differ")
  3709.     n <- length(xy$x)
  3710.     o <- order(xy$x)
  3711.     .C("lowess",
  3712.         x=as.double(xy$x[o]),
  3713.         as.double(xy$y[o]),
  3714.         n,
  3715.         as.double(f),
  3716.         as.integer(iter),
  3717.         as.double(delta),
  3718.         y=double(n),
  3719.         double(n),
  3720.         double(n))[c("x","y")]
  3721. }
  3722. lsfit <- function(x, y, wt=NULL, intercept=TRUE, tolerance=1e-07, yname=NULL)
  3723. {
  3724.     # find names of x variables (design matrix)
  3725.     x <- as.matrix(x)
  3726.     y <- as.matrix(y)
  3727.     xnames <- colnames(x)
  3728.     if( is.null(xnames) ) {
  3729.         if(ncol(x)==1) xnames <- "X"
  3730.         else xnames <- paste("X", 1:ncol(x), sep="")
  3731.     }
  3732.     if( intercept ) {
  3733.         x <- cbind(1, x)
  3734.         xnames <- c("Intercept", xnames)
  3735.     }
  3736.     # find names of y variables (responses)
  3737.     if(is.null(yname) && ncol(y) > 1) yname <- paste("Y", 1:ncol(y), sep="")
  3738.     # remove missing values
  3739.     good <- complete.cases(x, y, wt)
  3740.     dimy <- dim(as.matrix(y))
  3741.     if( any(!good) ) {
  3742.         warning(paste(sum(!good), "missing values deleted"))
  3743.         x <- as.matrix(x)[good, ]
  3744.         y <- as.matrix(y)[good, ]
  3745.         wt <- wt[good]
  3746.     }
  3747.     # check for compatible lengths
  3748.     nrx <- NROW(x)
  3749.     ncx <- NCOL(x)
  3750.     nry <- NROW(y)
  3751.     ncy <- NCOL(y)
  3752.     nwts <- length(wt)
  3753.     if(nry != nrx) stop(paste("X matrix has", nrx, "responses, Y",
  3754.             "has", nry, "responses."))
  3755.     if(nry < ncx) stop(paste(nry, "responses, but only", ncx, "variables"))
  3756.     # check weights if necessary
  3757.     if( !is.null(wt) ) {
  3758.         if(any(wt < 0)) stop("negative weights not allowed")
  3759.         if(nwts != nry) stop(paste("Number of weights =", nwts,
  3760.                 ", should equal", nry, "(number of responses)"))
  3761.         wtmult <- wt^0.5
  3762.         if( any(wt==0) ) {
  3763.             xzero <- as.matrix(x)[wt==0, ]
  3764.             yzero <- as.matrix(y)[wt==0, ]
  3765.         }
  3766.         x <- x*wtmult
  3767.         y <- y*wtmult
  3768.         invmult <- 1/ifelse(wt==0, 1, wtmult)
  3769.     }
  3770.     # call linpack
  3771.     storage.mode(x) <- "double"
  3772.     storage.mode(y) <- "double"
  3773.     z <- .Fortran("dqrls",
  3774.         qr=x,
  3775.         n=nrx,
  3776.         p=ncx,
  3777.         y=y,
  3778.         ny=ncy,
  3779.         tol=tolerance,
  3780.         coefficients=mat.or.vec(ncx, ncy),
  3781.         residuals=mat.or.vec(nrx, ncy),
  3782.         effects=mat.or.vec(nrx, ncy),
  3783.         rank=integer(1),
  3784.         pivot=as.integer(1:ncx),
  3785.         qraux=double(ncx),
  3786.         work=double(2*ncx))
  3787.     # dimension and name output from linpack
  3788.     resids <- array(NA, dim=dimy)
  3789.     dim(z$residuals) <- c(nry, ncy)
  3790.     if(!is.null(wt)) {
  3791.         if(any(wt==0)) {
  3792.             if(ncx==1) fitted.zeros <- xzero * z$coefficients
  3793.             else fitted.zeros <- xzero %*% z$coefficients
  3794.             z$residuals[wt==0, ] <- yzero - fitted.zeros
  3795.         }
  3796.         z$residuals <- z$residuals*invmult
  3797.     }
  3798.     resids[good, ] <- z$residuals
  3799.     if(dimy[2] == 1 && is.null(yname)) {
  3800.         resids <- as.vector(resids)
  3801.         names(z$coefficients) <- xnames
  3802.     }
  3803.     else {
  3804.         colnames(resids) <- yname
  3805.         colnames(z$effects) <- yname
  3806.         dim(z$coefficients) <- c(ncx, ncy)
  3807.         dimnames(z$coefficients) <- list(xnames, yname)
  3808.     }
  3809.     z$qr <- as.matrix(z$qr)
  3810.     colnames(z$qr) <- xnames
  3811.     output <- list(coef=z$coefficients, residuals=resids)
  3812.     # if X matrix was collinear, then the columns would have been
  3813.     # pivoted hence xnames need to be corrected
  3814.     if( z$rank != ncx ) {
  3815.         xnames <- xnames[z$pivot]
  3816.         dimnames(z$qr) <- list(NULL, xnames)
  3817.         warning("X matrix was collinear")
  3818.     }
  3819.     # return weights if necessary
  3820.     if (!is.null(wt) ) {
  3821.         weights <- rep(NA, dimy[1])
  3822.         weights[good] <- wt
  3823.         output <- c(output, list(wt=weights))
  3824.     }
  3825.     # return rest of output
  3826.     rqr <- list(qt=z$effects, qr=z$qr, qraux=z$qraux, rank=z$rank,
  3827.         pivot=z$pivot, tol=z$tol)
  3828.     output <- c(output, list(intercept=intercept, qr=rqr))
  3829.     return(output)
  3830. }
  3831. ls.diag <- function(ls.out)
  3832. {
  3833.     resids <- as.matrix(ls.out$residuals)
  3834.     xnames <- colnames(ls.out$qr$qr)
  3835.     yname <- colnames(resids)
  3836.     # remove any missing values
  3837.     good <- complete.cases(resids, ls.out$wt)
  3838.     if( any(!good) ) {
  3839.         warning("missing observations deleted")
  3840.         resids <- as.matrix(resids)[good, ]
  3841.     }
  3842.     # adjust residuals if needed
  3843.     if( !is.null(ls.out$wt) ) {
  3844.         if( any(ls.out$wt[good] == 0) )
  3845.             warning(paste("Observations with 0 weight not used in",
  3846.                 "calculating standard deviation"))
  3847.         resids <- resids * ls.out$wt[good]^0.5
  3848.     }
  3849.     # initialize
  3850.     p <- ls.out$qr$rank
  3851.     n <- nrow(resids)
  3852.     hatdiag <- rep(NA, NROW(ls.out$residuals))
  3853.     stats <- matrix(NA, nrow=NROW(ls.out$residuals), ncol=NCOL(resids))
  3854.     colnames(stats) <- yname
  3855.     stdres <- studres <- dfits <- Cooks <- stats
  3856.     # calculate hat matrix diagonals
  3857.     q <- qr.qy(ls.out$qr, rbind(diag(p), matrix(0, nrow=n-p, ncol=p)))
  3858.     hatdiag[good] <- apply(as.matrix(q^2), 1, sum)
  3859.     # calculate diagnostics
  3860.     stddev <- (apply(as.matrix(resids^2), 2, sum)/(n - p))^0.5
  3861.     stddevmat <- matrix(stddev, nrow=sum(good), ncol=ncol(resids), byrow=TRUE)
  3862.     stdres[good, ] <- resids/((1-hatdiag[good])^0.5 * stddevmat)
  3863.     studres[good, ] <- (stdres[good, ]*stddevmat)/(((n-p)*stddevmat^2 -
  3864.         resids^2/(1-hatdiag[good]))/(n-p-1))^0.5
  3865.     dfits[good, ] <- (hatdiag[good]/(1-hatdiag[good]))^0.5 * studres[good, ]
  3866.     Cooks[good, ] <- ((stdres[good, ]^2 * hatdiag[good])/p)/(1-hatdiag[good])
  3867.     if(ncol(resids)==1 && is.null(yname)) {
  3868.         stdres <- as.vector(stdres)
  3869.         Cooks <- as.vector(Cooks)
  3870.         studres <- as.vector(studres)
  3871.         dfits <- as.vector(dfits)
  3872.     }
  3873.     # calculate unscaled covariance matrix
  3874.     qr <- as.matrix(ls.out$qr$qr[1:p, 1:p])
  3875.     qr[row(qr)>col(qr)] <- 0
  3876.     qrinv <- solve(qr)
  3877.     covmat.unscaled <- qrinv%*%t(qrinv)
  3878.     dimnames(covmat.unscaled) <- list(xnames, xnames)
  3879.     # calculate scaled covariance matrix
  3880.     covmat.scaled <- sum(stddev^2) * covmat.unscaled
  3881.     # calculate correlation matrix
  3882.     cormat <- covmat.scaled/
  3883.         (outer(diag(covmat.scaled), diag(covmat.scaled))^0.5)
  3884.     # calculate standard error
  3885.     stderr <- outer(diag(covmat.unscaled)^0.5, stddev)
  3886.     dimnames(stderr) <- list(xnames, yname)
  3887.     return(list(std.dev=stddev, hat=hatdiag, std.res=stdres,
  3888.         stud.res=studres, cooks=Cooks, dfits=dfits,
  3889.         correlation=cormat, std.err=stderr,
  3890.         cov.scaled=covmat.scaled, cov.unscaled=covmat.unscaled))
  3891. }
  3892. ls.print <- function(ls.out, digits=4, print.it=TRUE)
  3893. {
  3894.     # calculate residuals to be used
  3895.     resids <- as.matrix(ls.out$residuals)
  3896.     if( !is.null(ls.out$wt) ) {
  3897.         if(any(ls.out$wt == 0))
  3898.             warning("Observations with 0 weights not used")
  3899.         resids <- resids * ls.out$wt^0.5
  3900.     }
  3901.     n <- apply(resids, 2, length)-apply(is.na(resids), 2, sum)
  3902.     p <- ls.out$qr$rank
  3903.     # calculate total sum sq and df
  3904.     if(ls.out$intercept) {
  3905.         if(is.matrix(ls.out$qr$qt))
  3906.             totss <- apply(ls.out$qr$qt[-1, ]^2, 2, sum)
  3907.         else totss <- sum(ls.out$qr$qt[-1]^2)
  3908.         degfree <- p - 1
  3909.     }
  3910.     else {
  3911.         totss <- apply(as.matrix(ls.out$qr$qt^2), 2, sum)
  3912.         degfree <- p
  3913.     }
  3914.     # calculate residual sum sq and regression sum sq
  3915.     resss <- apply(resids^2, 2, sum, na.rm=TRUE)
  3916.     resse <- (resss/(n-p))^.5
  3917.     regss <- totss - resss
  3918.     rsquared <- regss/totss
  3919.     fstat <- (regss/degfree)/(resss/(n-p))
  3920.     pvalue <- 1 - pf(fstat, degfree, (n-p))
  3921.     # construct summary
  3922.     summary <- cbind(format(round(resse, digits)), format(round(rsquared,
  3923.         digits)), format(round(fstat, digits)), format(degfree), format(
  3924.         n-p), format(round(pvalue, digits)))
  3925.     dimnames(summary) <- list(colnames(ls.out$residuals), c("Mean Sum Sq",
  3926.         "R Squared", "F-value", "Df 1", "Df 2", "Pr(>F)"))
  3927.     mat <- as.matrix(ls.out$qr$qr[1:p, 1:p])
  3928.     mat[row(mat)>col(mat)] <- 0
  3929.     qrinv <- solve(mat)
  3930.     # construct coef table
  3931.     coef.table <- as.list(1:ncol(ls.out$residuals))
  3932.     if(ncol(ls.out$residuals)==1) coef <- matrix(ls.out$coef, nc=1)
  3933.     else coef <- ls.out$coef
  3934.     for(i in 1:ncol(ls.out$residuals)) {
  3935.         covmat <- (resss[i]/(n[i]-p)) * (qrinv%*%t(qrinv))
  3936.         coef.table[[i]] <- cbind(coef[, i], diag(covmat)^.5,
  3937.             coef[, i]/diag(covmat)^.5,
  3938.             2*(1 - pt(abs(coef[, i]/diag(covmat)^.5), n[i]-p)))
  3939.         dimnames(coef.table[[i]]) <- list(colnames(ls.out$qr$qr),
  3940.             c("Estimate", "Std.Err", "t-value", "Pr(>|t|)"))
  3941.         #print results
  3942.         if(print.it) {
  3943.             if(ncol(ls.out$residuals)>1)
  3944.                 cat("Response:", colnames(ls.out$residuals)[i],
  3945.                 "\n\n")
  3946.             cat(paste("Residual Standard Error=", format(round(
  3947.                 resse[i], digits)), "\nR-Square=", format(round(
  3948.                 rsquared[i], digits)), "\nF-statistic (df=",
  3949.                 format(degfree), ", ", format(n[i]-p), ")=",
  3950.                 format(round(fstat[i], digits)), "\np-value=",
  3951.                 format(round(pvalue[i], digits)), "\n\n", sep=""))
  3952.             print(round(coef.table[[i]], digits))
  3953.             cat("\n\n")
  3954.         }
  3955.     }
  3956.     names(coef.table) <- colnames(ls.out$residuals)
  3957.     invisible(list(summary=summary, coef.table=coef.table))
  3958. }
  3959. macintosh <- function() .Internal(device("Macintosh","",c(0,0,0)))
  3960. mad <- function(y, center, constant = 1.4826, na.rm = FALSE) {
  3961.     if(na.rm)
  3962.         y <- y[!is.na(y)]
  3963.     if(missing(center))
  3964.         constant * (median(abs(y - median(y))))
  3965.     else constant * (median(abs(y - center)))
  3966. }
  3967. match <- function(x, table, nomatch=NA)
  3968.         .Internal(match(x, table, nomatch))
  3969. match.call <- function(definition=NULL,call=sys.call(sys.parent()),
  3970. expand.dots=T)
  3971.         .Internal(match.call(definition,call,expand.dots))
  3972. pmatch <- function(x, table, nomatch=NA) {
  3973.     y<-.Internal(pmatch(x,table))
  3974.     y[is.na(y)]<-nomatch
  3975.     y
  3976. }
  3977. match.arg <- function(arg, choices) {
  3978.         if (missing(choices)) {
  3979.                 formal.args <- formals(sys.function(sys.parent()))
  3980.                 choices <- eval(formal.args[[deparse(substitute(arg))]])
  3981.         }
  3982.         rval <- choices[pmatch(arg, choices)]
  3983.         if (is.na(rval)) {
  3984.                 stop(paste("argument should be one of",
  3985.             paste(choices,collapse=", "), sep = " "))
  3986.         }
  3987.     if( length(rval) > 1 ) {
  3988.         if(arg==choices)
  3989.             rval<-choices[1]
  3990.         else
  3991.             stop("there is more than one match in match.arg")
  3992.     }
  3993.         return(rval)
  3994. }
  3995. #just for compatiblity we have charmatch and char.expand
  3996. charmatch <- pmatch
  3997. char.expand <- function(input, target, nomatch = stop("no match"))
  3998. {
  3999.     if(length(input) != 1)
  4000.         stop("char.expand: input must have length 1")
  4001.     if(!(is.character(input) && is.character(target)))
  4002.         stop("char.expand: input must be character")
  4003.     y<-.Internal(pmatch(input,target))
  4004.     if(any(is.na(y))) eval(nomatch)
  4005.     target[y]
  4006. }
  4007. matrix <- function(data=NA, nrow=1, ncol=1, byrow=FALSE, dimnames=NULL) {
  4008.                 if(missing(nrow)) nrow <- ceiling(length(data)/ncol)
  4009.                 else if(missing(ncol)) ncol <- ceiling(length(data)/nrow)
  4010.                 x <- .Internal(matrix(data, nrow, ncol, byrow))
  4011.                 levels(x) <- levels(data)
  4012.                 dimnames(x)<-dimnames
  4013.                 x
  4014. }
  4015. nrow <- function(x) dim(x)[1]
  4016. ncol <- function(x) dim(x)[2]
  4017. NROW <- function(x) if(is.matrix(x)) nrow(x) else length(x)
  4018. NCOL <- function(x) if(is.matrix(x)) ncol(x) else as.integer(1)
  4019. rownames <- function(x) {
  4020.     dn <- dimnames(x)
  4021.     if(is.null(dn)) dn else dn[[1]]
  4022. }
  4023. "rownames<-" <- function(x, value) {
  4024.     dn <- dimnames(x)
  4025.     if(is.null(dn)) dimnames(x) <- list(value, dn)
  4026.     else dimnames(x) <- list(value, dn[[2]])
  4027.     x
  4028. }
  4029. colnames <- function(x) {
  4030.     dn <- dimnames(x)
  4031.     if(is.null(dn)) dn else dn[[2]]
  4032. }
  4033. "colnames<-" <- function(x, value) {
  4034.     dn <- dimnames(x)
  4035.     if(is.null(dn)) dimnames(x) <- list(dn, value)
  4036.     else dimnames(x) <- list(dn[[1]], value)
  4037.     x
  4038. }
  4039. row <- function(x, as.factor=FALSE) {
  4040.     if(as.factor) factor(.Internal(row(x)), labels=rownames(x))
  4041.     else .Internal(row(x))
  4042. }
  4043. col <- function(x, as.factor=FALSE) {
  4044.     if(as.factor) factor(.Internal(col(x)), labels=colnames(x))
  4045.     else .Internal(col(x))
  4046. }
  4047. crossprod <-
  4048. function(x, y=x)
  4049. .Internal(crossprod(x,y))
  4050. t <- function(x)
  4051.  UseMethod("t")
  4052. t.data.frame<- function(x)
  4053. {
  4054.         x <- as.matrix(x)
  4055.         NextMethod("t")
  4056. }
  4057. mean <- function(x, trim = 0, na.rm = FALSE) {
  4058.         if (na.rm)
  4059.                 x<-x[!is.na(x)]
  4060.         trim <- trim[1]
  4061.     if(trim > 0) {
  4062.         if(trim >= 0.5) return(median(x, na.rm=FALSE))
  4063.         lo <- floor(length(x)*trim)+1
  4064.         hi <- length(x)+1-lo
  4065.         x <- sort(x, partial=unique(c(lo, hi)))[lo:hi]
  4066.     }
  4067.         sum(x)/length(x)
  4068. }
  4069. weighted.mean <- function(x, w, na.rm = FALSE ){
  4070.     if(missing(w)) w <- rep(1,length(x))
  4071.     if (na.rm) {
  4072.         w<-w[!is.na(x)]
  4073.         x<-x[!is.na(x)]
  4074.     }
  4075.     sum(x*w)/sum(w)
  4076. }
  4077. median <- function(x, na.rm = FALSE) {
  4078.     if(na.rm)
  4079.         x <- x[!is.na(x)]
  4080.     else if(any(is.na(x)))
  4081.         return(NA)
  4082.     n <- length(x)
  4083.     half <- (n + 1)/2
  4084.     if(n %% 2 == 1) {
  4085.         sort(x, partial = half)[half]
  4086.     }
  4087.     else {
  4088.         sum(sort(x, partial = c(half, half + 1))[c(half, half + 1)])/2
  4089.     }
  4090. }
  4091. menu<-function(x)
  4092. {
  4093.     xlen<-length(x)
  4094.     cat("\n")
  4095.     for(i in 1:xlen) 
  4096.         cat(i,":",x[i],"\n",sep="")
  4097.     done<-0
  4098.     repeat {
  4099.         cat("Selection: ")
  4100.         ind<-.Internal(menu(as.character(x)))
  4101.         if(ind<=xlen)
  4102.             return(ind)
  4103.         cat("Enter an item from the menu, or 0 to exit\n")
  4104.     }
  4105. }
  4106. mode <- function(x) {
  4107.     if (is.expression(x)) return("expression")
  4108.     tx <- typeof(x)
  4109.     if (tx == "real" ) return("numeric")
  4110.     if (tx == "integer") return("numeric")
  4111.     if (tx == "closure" || tx == "builtin" ) return("function")
  4112.     if (tx == "language") {
  4113.         if(is.call(x)) return("call")
  4114.         if(is.name(x)) return("name")
  4115.     }
  4116.     tx
  4117. }
  4118. "mode<-" <- function(x, value) 
  4119. {
  4120.     mde <- paste("as.",value,sep="")
  4121.     atr <- attributes(x)
  4122.     x <- eval(call(mde,x), sys.frame(sys.parent()))
  4123.     attributes(x) <- atr
  4124.     x
  4125. }
  4126. storage.mode <- function(x) {
  4127.         x <- typeof(x)
  4128.     if (x == "closure" || x == "builtin" ) return("function")
  4129.     x
  4130. }
  4131. "storage.mode<-" <- get("mode<-")
  4132. formula <- function(x, ...) UseMethod("formula")
  4133. formula.default <- function(x) {
  4134.     if (!is.null(x$formula))
  4135.         eval(x$formula)
  4136.     switch(typeof(x),
  4137.         NULL = structure(NULL, class="formula"),
  4138.         character = formula(eval(parse(text=x)[[1]])),
  4139.         call = eval(x),
  4140.         stop("invalid formula"))
  4141. }
  4142. formula.formula <- function(x) x
  4143. formula.terms <- function(x) {
  4144.     attributes(x) <- list(class="formula")
  4145.     x
  4146. }
  4147. print.formula <- function(x) print.default(unclass(x))
  4148. terms <- function(x, ...) UseMethod("terms")
  4149. print.terms <- function(x) print.default(unclass(x))
  4150. terms.default <- function(x) x$terms
  4151. terms.terms <- function(x) x
  4152. delete.response <-
  4153. function (termobj) 
  4154.     terms(reformulate(attr(termobj, "term.labels"), NULL),
  4155.         specials=names(attr(termobj, "specials")))
  4156. reformulate <- 
  4157. function (termlabels, response=NULL) 
  4158. {
  4159.     if (is.null(response)){
  4160.         termtext <- paste("~", paste(termlabels, collapse="+"),collapse="")
  4161.         termobj <- eval(parse(text=termtext)[[1]])
  4162.     }
  4163.     else {
  4164.         termtext <- paste("response", "~", paste(termlabels, collapse="+"), 
  4165.             collapse="")
  4166.         termobj <- eval(parse(text=termtext)[[1]])
  4167.         termobj[[2]] <- response
  4168.     }
  4169.     termobj
  4170. }
  4171. drop.terms <-
  4172. function(termobj, dropx=NULL, keep.response=FALSE) 
  4173. {
  4174.     if (is.null(dropx)) 
  4175.         termobj
  4176.     else {
  4177.         newformula <- reformulate(attr(termobj, "term.labels")[-dropx], if (keep.response) termobj[[2]] else NULL)
  4178.         terms(newformula, specials=names(attr(termobj, "specials")))
  4179.     }
  4180. }
  4181. terms.formula <-
  4182. function (x, specials = NULL, abb = NULL, data = NULL, keep.order = FALSE) 
  4183. {
  4184.     new.specials <- unique(c(specials, "offset"))
  4185.     terms <- .Internal(terms.formula(x, new.specials, abb, data, keep.order))
  4186.     offsets <- attr(terms,"specials")$offset
  4187.     if(!is.null(offsets)) {
  4188.         names <- dimnames(attr(terms,"factors"))[[1]][offsets]
  4189.         offsets <- match(names, dimnames(attr(terms,"factors"))[[2]])
  4190.         offsets <- offsets[!is.na(offsets)]
  4191.         if(length(offsets) > 0) {
  4192.             attr(terms, "factors") <- attr(terms,"factors")[,-offsets, drop=FALSE]
  4193.             attr(terms, "term.labels") <- attr(terms, "term.labels")[-offsets]
  4194.             attr(terms, "order") <- attr(terms, "order")[-offsets]
  4195.             attr(terms, "offset") <- attr(terms,"specials")$offset
  4196.         }
  4197.     }
  4198.     attr(terms, "specials")$offset <- NULL
  4199.     terms
  4200. }
  4201. coefficients <- function(x, ...)
  4202. UseMethod("coefficients")
  4203. coef <- coefficients
  4204. residuals <- function(x, ...) 
  4205. UseMethod("residuals")
  4206. resid <- residuals
  4207. deviance <- function(x, ...)
  4208. UseMethod("deviance")
  4209. fitted.values <- function(x, ...) 
  4210. UseMethod("fitted.values")
  4211. fitted <- fitted.values
  4212. anova <- function(x, ...)
  4213. UseMethod("anova")
  4214. effects <- function(x, ...)
  4215. UseMethod("effects")
  4216. weights <- function(x, ...)
  4217. UseMethod("weights")
  4218. df.residual <- function(x, ...)
  4219. UseMethod("df.residual")
  4220. offset <- function(x) x
  4221. na.action <- function(x, ...)
  4222. UseMethod("na.action")
  4223. na.action.default <- function(x) attr(x, "na.action")
  4224. na.fail <- function(frame)
  4225. {
  4226.     ok <- complete.cases(frame)
  4227.     if(all(ok)) frame else stop("missing values in data frame");
  4228. }
  4229. na.omit <- function(frame)
  4230. {
  4231.     ok <- complete.cases(frame)
  4232.     if (all(ok))
  4233.         return(frame)
  4234.     else return(frame[ok, ])
  4235. }
  4236. model.data.frame <- function(...) {
  4237.     cn <- as.character(substitute(list(...))[-1])
  4238.     data.frame(..., col.names=cn, as.is=TRUE)
  4239. }
  4240. "model.frame" <-
  4241. function (formula, data = sys.frame(sys.parent()), subset = NULL,
  4242.     na.action = eval(as.name(options("na.action")$na.action)), 
  4243.     use.data = TRUE, process.offsets = TRUE, ...) 
  4244.         if (!is.null(formula$model) && missing(data)) 
  4245.       return(formula$model)
  4246.     if (!missing(data) || is.null(formula$model.frame)) {
  4247.         dotsdata <- if (use.data) 
  4248.             data
  4249.         else sys.frame(sys.parent())
  4250.         newframe <- substitute(list(...))
  4251.         dots <- eval(newframe, dotsdata)
  4252.         if (!is.null(dots)) {
  4253.             real.dots <- !unlist(lapply(dots, is.null))
  4254.             newframe <- as.call(newframe[c(T, real.dots)])
  4255.             dots <- dots[real.dots]
  4256.         }
  4257.         Terms <- terms(formula)
  4258.         frame <- attr(Terms, "variables")
  4259.         name.process <- function(x) paste("(", x, ")", sep = "")
  4260.         if (missing(data) && !is.null(formula$call)) {
  4261.             if (is.null(formula$call$data))
  4262.                 data<-environment(NULL)
  4263.             else
  4264.                 data <- eval(formula$call$data)
  4265.         }
  4266.         if (!(missing(subset) || exists(as.character(match.call()$subset), inherits = FALSE))) 
  4267.             subset <- eval(match.call()$subset, data)
  4268.         if (is.null(dots)) 
  4269.             rval <- na.action(eval(frame, data)[subset, , drop = FALSE])
  4270.         else {
  4271.             dotnames <- sapply(names(eval(dots, data)), name.process)
  4272.             val <- eval(frame, data)
  4273.             newframe[[1]] <- as.name("model.data.frame")
  4274.             for (i in 1:length(dots)) newframe[[i + 1]] <- dots[[i]]
  4275.             dotsval <- eval(newframe, dotsdata)
  4276.             names(dotsval) <- dotnames
  4277.             if (dim(val)[1] == dim(dotsval)[1]) 
  4278.                 newval <- c(val, dotsval)
  4279.             else stop("Mismatched dimensions in model.frame")
  4280.             class(newval) <- "data.frame"
  4281.             rval <- na.action(newval[subset, , drop = FALSE])
  4282.         }
  4283.         attr(rval, "terms") <- Terms
  4284.         offset.pos <- attr(Terms, "offset")
  4285.         if (process.offsets && (length(offset.pos) > 0)) {
  4286.             offset.total <- as.vector(as.matrix(rval[, offset.pos]) %*% rep(1, length(offset.pos
  4287.             )))
  4288.             rval[[offset.pos[1]]] <- offset.total
  4289.             names(rval)[offset.pos[1]] <- "(offset)"
  4290.         }
  4291.         rval
  4292.     }
  4293.     else formula$model.frame
  4294. }
  4295. model.weights <- function(x) x$"(weights)"
  4296. model.offset <- function(x) x$"(offset)"
  4297. model.matrix <- function (formula, data) 
  4298. {
  4299.     t <- terms(formula)
  4300.     if (missing(data)) 
  4301.         data <- eval(attr(t, "variables"), sys.frame(sys.parent()))
  4302.     .Internal(model.matrix(t, data))
  4303. }
  4304. model.response <- function(data, type="numeric")
  4305. {
  4306.     if(attr(attr(data,"terms"), "response")) {
  4307.         if(is.list(data) | is.data.frame(data)) {
  4308.             v <- data[[1]]
  4309.             if(type == "numeric" | type == "double") {
  4310.                 storage.mode(v) <- "double"
  4311.             }
  4312.             else stop("invalid response type")
  4313.             if(is.matrix(v) && ncol(v) == 1)
  4314.                 dim(v) <- NULL
  4315.             return(v)
  4316.         }
  4317.         else stop("invalid data argument")
  4318.     }
  4319.     else
  4320.         return (NULL)
  4321. }
  4322. model.extract <- function(frame, component)
  4323. {
  4324.     component<-as.character(substitute(component))
  4325.     rval<-switch(component,
  4326.         response= model.response(frame),
  4327.         offset = model.offset(frame),
  4328.         weights = frame$"(weights)",
  4329.         start = frame$"(start)"
  4330.         )
  4331.     if(length(rval) == nrow(frame))
  4332.         names(rval)<-attr(frame, "row.names")
  4333.     else if(is.matrix(rval) && nrow(rval)==nrow(frame)) {
  4334.         t1<-dimnames(rval)
  4335.         dimnames(rval)<-list(attr(frame, "row.names"),t1[[2]])
  4336.     }
  4337.     return(rval)
  4338. }
  4339. update <-
  4340. function(x, ...)
  4341.     UseMethod("update")
  4342. mtext <- function(text, side=3, line=0, outer=FALSE, at=NULL, ...)
  4343.   .Internal(mtext(text, side, line, outer, at, ...))
  4344. named.elements <-
  4345. function(x)
  4346. {
  4347.     n <- names(x)
  4348.     if(is.null(n)) NULL
  4349.     else !is.na(n)
  4350. }
  4351. names <-
  4352. function(x, ...)
  4353. UseMethod("names")
  4354. names.default <-
  4355. function(x)
  4356. .Internal(names(x))
  4357. "names<-" <-
  4358. function(x, ...)
  4359. UseMethod("names<-")
  4360. "names<-.default" <- 
  4361. function(x, n)
  4362. .Internal("names<-"(x, n))
  4363. nlm <-
  4364. function(f, p, hessian=FALSE, typsiz=rep(1,length(p)),
  4365.     fscale=1, print.level=0, ndigit=12, gradtl=1.e-6,
  4366.     stepmx=max(1000 * sqrt(sum((p/typsiz)^2)), 1000),
  4367.     steptl=1.e-6, itnlim=100)
  4368. {
  4369.     if(print.level == 0) msg <- msg <- 9
  4370.     else if(print.level == 1) msg <- 1
  4371.     else if(print.level == 2) msg <- 17
  4372.     .Internal(nlm(f, p, hessian, typsiz, fscale, msg, ndigit, gradtl,
  4373.         stepmx, steptl, itnlim))
  4374. }
  4375. optimize <-
  4376. function(f, interval, lower=min(interval), upper=max(interval),
  4377.     maximum=FALSE, tol=.Machine$double.eps^0.25, ...)
  4378. {
  4379.     if(maximum) {
  4380.         val <- .Internal(fmin(function(arg) -f(arg, ...), lower, upper, tol))
  4381.         list(maximum=val, objective=-f(val, ...))
  4382.     }
  4383.     else {
  4384.         val <- .Internal(fmin(function(arg) f(arg, ...), lower, upper, tol))
  4385.         list(minimum=val, objective=f(val, ...))
  4386.     }
  4387. }
  4388. uniroot <-
  4389. function(f, interval, lower=min(interval), upper=max(interval), tol=.Machine$double.eps^0.25, ...)
  4390. {
  4391.     if(f(interval[1], ...)*f(interval[2], ...) >= 0)
  4392.         stop("signs at end points not of opposite sign")
  4393.     val <- .Internal(zeroin(function(arg) f(arg, ...), lower, upper, tol))
  4394.     list(root=val, f.root=f(val, ...))
  4395. }
  4396. deriv <- function(x, ...)
  4397. UseMethod("deriv")
  4398. deriv.formula <- function(expr, namevec, function.arg=NULL, tag=".expr") {
  4399. if(length(expr) == 2) .Internal(deriv.default(expr[[2]], namevec, function.arg, tag))
  4400. else stop("invalid formula in deriv")
  4401. }
  4402. deriv.default <- function(expr, namevec, function.arg=NULL, tag=".expr")
  4403. .Internal(deriv.default(expr, namevec, function.arg, tag))
  4404. inherits <-
  4405. function(x, name)
  4406. {
  4407.     if(is.object(x)) any(!is.na(match(name,class(x))))
  4408.     else FALSE
  4409. }
  4410. NextMethod <-
  4411. function(generic=NULL, object=NULL, ...)
  4412.     .Internal(NextMethod(generic, object,...))
  4413. methods <-
  4414. function (generic.function, class) 
  4415. {
  4416.     allnames <- unique(c(ls(.SystemEnv), ls(.GlobalEnv)))
  4417.     if (!missing(generic.function)) {
  4418.         if (!is.character(generic.function)) 
  4419.             generic.function <- deparse(substitute(generic.function))
  4420.         name <- paste("^", generic.function, ".", sep = "")
  4421.     }
  4422.     else if (!missing(class)) {
  4423.         if (!is.character(class)) 
  4424.             class <- paste(deparse(substitute(class)))
  4425.         name <- paste(".", class, "$", sep = "")
  4426.     }
  4427.     else stop("must supply generic.function or class")
  4428.     grep(gsub("\\.", "\\\\.", name), allnames, value = TRUE)
  4429. }
  4430. options <-
  4431. function(...) .Internal(options(...))
  4432. outer <- function(x, y, FUN="*", ...) {
  4433.         if(is.character(FUN))
  4434.                 FUN <- get(FUN, mode="function", inherits=TRUE)
  4435.         nr <- length(x)
  4436.         nc <- length(y)
  4437.         matrix(
  4438.                 FUN(matrix(x, nr, nc), matrix(y, nr, nc, byrow=TRUE), ...),
  4439.                 nr, nc)
  4440. }
  4441. "%o%"<-outer
  4442. pairs <- function (x, labels, panel=points, main = NULL, font.main=par("font.main"),
  4443.     cex.main=par("cex.main"), ...) 
  4444. {
  4445.     if(!is.matrix(x)) x <- data.matrix(x)
  4446.     if(!is.numeric(x)) stop("non-numeric argument to pairs")
  4447.     nc <- ncol(x)
  4448.     if(nc < 2) stop("only one column in the argument to pairs")
  4449.     if (missing(labels)) {
  4450.         labels <- dimnames(x)[[2]]
  4451.         if (is.null(labels)) 
  4452.             labels <- paste("var", 1:nc)
  4453.     }
  4454.     oma <- c(4, 4, 4, 4)
  4455.     if (!is.null(main)) 
  4456.         oma[3] <- 6
  4457.     opar <- par(mfrow = c(nc, nc), mar = rep(0.5, 4), oma = oma)
  4458.     on.exit(par(opar))
  4459.     for (i in 1:nc) for (j in 1:nc) {
  4460.         if (i == j) {
  4461.             plot(x[, j], x[, i], xlab = "", ylab = "", axes = FALSE, type = "n", 
  4462.                 ...)
  4463.             box()
  4464.             text(mean(par("usr")[1:2]), mean(par("usr")[3:4]), labels[i])
  4465.         }
  4466.         else {
  4467.             plot(x[, j], x[, i], type="n", xlab = "", ylab = "", axes = FALSE, ...)
  4468.             box()
  4469.             panel(x[, j], x[, i], ...)
  4470.         }
  4471.         if (j == 1 & 2 * floor(i/2) == i) 
  4472.             axis(2)
  4473.         if (i == 1 & 2 * floor(j/2) == j) 
  4474.             axis(3)
  4475.         if (j == nc & 2 * floor(i/2) != i) 
  4476.             axis(4)
  4477.         if (i == nc & 2 * floor(j/2) != j) 
  4478.             axis(1)
  4479.     }
  4480.     if (!is.null(main)) mtext(main, 3, 3, T, 0.5,
  4481.         cex=cex.main/par("cex"), font=font.main)
  4482.     invisible(NULL)
  4483. }
  4484. .Pars <- c(
  4485. "1em", "adj", "ask", "bty", "cex", "cin", "col", "cra", "crt", "csi",
  4486. "cxy", "din", "err", "exp", "fig", "fin", "font", "frm", "fty", "lab",
  4487. "las", "lty", "lwd", "mai", "mar", "mex", "mfg", "mgp", "new", "oma",
  4488. "omd", "omi", "pch", "pin", "plt", "pty", "rsz", "smo", "srt", "tck",
  4489. "uin", "usr", "xaxp", "xaxs", "xaxt", "xpd", "yaxp", "yaxs", "yaxt")
  4490. ##>> R-alpha  0.16.1
  4491. ##>>  pp_ par(); names(pp[sapply(pp,is.null)])
  4492. ##>>  [1] "1em" "cxy" "din" "exp" "frm" "fty" "rsz" "uin"
  4493. ##>>       ---   ---   ---   ---   ---   ---   ---   ---  
  4494. ##-- These are the ones used in 0.16.1 -- $RHOME/src/main/par.c  Query(..) :
  4495. .Pars <- c(
  4496. "adj", "ann", "ask", "bg", "bty",
  4497. "cex", "cex.axis", "cex.lab", "cex.main", "cex.sub", "cin",
  4498. "col", "col.axis", "col.lab", "col.main", "col.sub", "cra", "crt", "csi",
  4499. "err", "fg", "fig", "fin",
  4500. "font", "font.axis", "font.lab", "font.main", "font.sub", "lab", "las",
  4501. "lty", "lwd", "mai", "mar", "mex", "mfcol", "mfg", "mfrow", "mgp", "mkh",
  4502. "new", "oma", "omd", "omi", "pch", "pin", "plt", "ps", "pty",
  4503. "smo", "srt", "tck", "tmag", "type", "usr",
  4504. "xaxp", "xaxs", "xaxt", "xlog", "xpd",
  4505. "yaxp", "yaxs", "yaxt", "ylog")
  4506. par <-
  4507. function (...)
  4508. {
  4509.     single <- FALSE
  4510.     if (nargs() == 0) {
  4511.         args <- as.list(.Pars)
  4512.     }
  4513.     else {
  4514.         args <- list(...)
  4515.         if (length(args) == 1) {
  4516.             if (is.list(args[[1]]) | is.null(args[[1]]))
  4517.                 args <- args[[1]]
  4518.             else
  4519.                 if(is.null(names(args)))
  4520.                     single <- TRUE
  4521.         }
  4522.     }
  4523.     value <- if (single) .Internal(par(args))[[1]]
  4524.     else .Internal(par(args))
  4525.         if(!is.null(names(args))) invisible(value) else value
  4526. }
  4527. par2 <-
  4528. function (...) 
  4529. {
  4530.     args <- list(...)
  4531.     if (length(args) == 1 && is.list(args[[1]])) 
  4532.         args <- args[[1]]
  4533.     .Internal(par2(args))
  4534. }
  4535. #we don't use white; it's for compatibility
  4536. parse <- function(file="", n=NULL, text=NULL, prompt=NULL, white=FALSE)
  4537. as.expression(.Internal(parse(file, n, text, prompt)))
  4538. "[.expression"<-function(x,subs)
  4539.     structure(unclass(x)[subs],class="expression")
  4540. "[[.expression"<-function(x,subs)
  4541.     unclass(x)[[subs]]
  4542. is.expression<-function(x)
  4543.     inherits(x,"expression")
  4544. as.expression<-function(x)
  4545. {
  4546.     if(is.null(x) || is.expression(x)) 
  4547.         x
  4548.     else 
  4549.         structure(as.list(x),class="expression")
  4550. }
  4551. expression <- function(...){
  4552.     y<-substitute(list(...))[-1]
  4553.     structure(y,class="expression")
  4554. }
  4555. print.expression<-function(x)
  4556. {
  4557.     print(as.call(c(as.name("expression"),x)))
  4558. }
  4559. paste <- function (..., sep = " ", collapse=NULL) 
  4560. {
  4561.         args <- list(...)
  4562.     if(is.null(args)) ""
  4563.     else {
  4564.         for (i in 1:length(args)) args[[i]] <- as.character(args[[i]])
  4565.         .Internal(paste(args, sep, collapse))
  4566.     }
  4567. }
  4568. pictex <-
  4569. function(file="Rplots.tex", width=5, height=4, debug = FALSE,
  4570.         bg="white", fg="black")
  4571. {
  4572.         .Internal(device("pictex", as.character(c(file)),
  4573.                 c(width, height, debug, bg, fg)))
  4574.         par(mar=c(5,4,2,4)+0.1)
  4575. }
  4576. piechart <- function (x, labels=names(x), edges=200,
  4577.     radius=0.8, col=NULL, main=NULL, ...)
  4578. {
  4579.     if (any(is.na(x) | x <= 0))
  4580.         stop("invalid values in pie")
  4581.     if (is.null(labels))
  4582.         labels <- as.character(1:length(x))
  4583.     x <- c(0, cumsum(x)/sum(x))
  4584.     dx <- diff(x)
  4585.     twopi <- 8 * atan(1)
  4586.     pin <- par("pin")
  4587.     xlim <- c(-1, 1)
  4588.     ylim <- c(-1, 1)
  4589.     if (pin[1] > pin[2]) xlim <- (pin[1]/pin[2]) * xlim
  4590.     else ylim <- (pin[2]/pin[1]) * ylim
  4591.     plot.new()
  4592.     plot.window(xlim, ylim, "")
  4593.     for (i in 1:length(dx)) {
  4594.         n <- floor(edges * dx[i])
  4595.         t <- seq(x[i], x[i + 1], length = n)
  4596.         xc <- c(cos(twopi * t), 0) * radius
  4597.         yc <- c(sin(twopi * t), 0) * radius
  4598.         polygon(xc, yc, col=col[(i-1)%%length(col)+1])
  4599.         t <- mean(x[i + 0:1])
  4600.         xc <- cos(twopi * t) * radius
  4601.         yc <- sin(twopi * t) * radius
  4602.         lines(c(1,1.05)*xc, c(1,1.05)*yc)
  4603.         text(1.1*xc, 1.1*yc, labels[i], xpd = TRUE, adj = ifelse(xc < 0, 1, 0))
  4604.     }
  4605.     title(main = main, ...)
  4606.     invisible(NULL)
  4607. }
  4608. xy.coords <- function(x, y, xlab=NULL, ylab=NULL) {
  4609.     if(is.null(y)) {
  4610.         ylab<- xlab
  4611.         if(is.language(x)) {
  4612.             if(length(x) == 3 && deparse(x[[1]]) == '~') {
  4613.                 ylab <- deparse(x[[2]])
  4614.                 xlab <- deparse(x[[3]])
  4615.                 y <- eval(x[[2]], sys.frame(sys.parent()))
  4616.                 x <- eval(x[[3]], sys.frame(sys.parent()))
  4617.             }
  4618.             else stop("invalid first argument")
  4619.         }
  4620.         else if(is.ts(x)) {
  4621.             if(is.matrix(x)) y <- x[,1]
  4622.             else y <- x
  4623.             x <- time(x)
  4624.             xlab <- "Time"
  4625.         }
  4626.         else if(is.complex(x)) {
  4627.             y <- Im(x)
  4628.             x <- Re(x)
  4629.             xlab <- paste("Re(", ylab, ")", sep="")
  4630.             ylab <- paste("Im(", ylab, ")", sep="")
  4631.         }
  4632.         else if(is.matrix(x) || is.data.frame(x)) {
  4633.             x <- data.matrix(x)
  4634.             if(ncol(x) == 1) {
  4635.                 xlab <- "Index"
  4636.                 y <- x[,1]
  4637.                 x <- 1:length(y)
  4638.             }
  4639.             else {
  4640.                 colnames <- dimnames(x)[[2]]
  4641.                 if(is.null(colnames)) {
  4642.                     xlab <- paste(ylab,"[,1]",sep="")
  4643.                     ylab <- paste(ylab,"[,2]",sep="")
  4644.                 }
  4645.                 else {
  4646.                     xlab <- colnames[1]
  4647.                     ylab <- colnames[2]
  4648.                 }
  4649.                 y <- x[,2]
  4650.                 x <- x[,1]
  4651.             }
  4652.         }
  4653.         else if(is.list(x)) {
  4654.             xlab <- paste(ylab,"$x",sep="")
  4655.             ylab <- paste(ylab,"$y",sep="")
  4656.             y <- x[["y"]]
  4657.             x <- x[["x"]]
  4658.         }
  4659.         else {
  4660.             if(is.factor(x)) x <- as.numeric(x)
  4661.             xlab <- "Index"
  4662.             y <- x
  4663.             x <- 1:length(x)
  4664.         }
  4665.     }
  4666.     else if(length(x) != length(y)) stop("x and y lengths differ")
  4667.     return(list(x=as.real(x), y=as.real(y), xlab=xlab, ylab=ylab))
  4668. }
  4669. plot <- function(x, ...)
  4670. UseMethod("plot")
  4671. plot.default <-
  4672. function (x, y=NULL, type="p", col=par("fg"), bg=NA, pch=par("pch"), xlim=NULL,
  4673.     ylim=NULL, log="", axes=TRUE, frame.plot=TRUE, panel.first=NULL,
  4674.     panel.last=NULL, ann=par("ann"), main=NULL, xlab=NULL, ylab=NULL,
  4675.     cex=par("cex"), lty=par("lty"), ...) 
  4676. {
  4677.     xlabel <- if (!missing(x)) 
  4678.         deparse(substitute(x))
  4679.     else NULL
  4680.     ylabel <- if (!missing(y)) 
  4681.         deparse(substitute(y))
  4682.     else NULL
  4683.     xy <- xy.coords(x, y, xlabel, ylabel)
  4684.     xlab <- if (missing(xlab)) 
  4685.         xy$xlab
  4686.     else xlab
  4687.     ylab <- if (missing(ylab)) 
  4688.         xy$ylab
  4689.     else ylab
  4690.     xlim <- if (missing(xlim)) 
  4691.         range(xy$x, na.rm=TRUE)
  4692.     else xlim
  4693.     ylim <- if (missing(ylim)) 
  4694.         range(xy$y, na.rm=TRUE)
  4695.     else ylim
  4696.     plot.new()
  4697.     plot.window(xlim, ylim, log, ...)
  4698.     panel.first
  4699.     plot.xy(xy, type, col=col, pch=pch, cex=cex, bg=bg, lty=lty, ...)
  4700.     panel.last
  4701.     if (axes) {
  4702.         axis(1, ...)
  4703.         axis(2, ...)
  4704.         if (frame.plot) 
  4705.             box(...)
  4706.     }
  4707.     if (ann) 
  4708.         title(main=main, xlab=xlab, ylab=ylab, ...)
  4709.     invisible()
  4710. }
  4711. plot.factor <-
  4712. function(x, y, ...)
  4713. {
  4714.     if(missing(y))
  4715.         barplot(table(x), ...)
  4716.     else NextMethod("plot")
  4717. }
  4718. plot.xy <- function(xy, type, pch=1, lty="solid", col=par("fg"), bg=NA, cex=1, ...)
  4719.     .Internal(plot.xy(xy, type, pch, lty, col, bg=bg, cex, ...))
  4720. plot.new <- function(ask=NA)
  4721.     .Internal(plot.new(ask))
  4722. frame <- plot.new
  4723. pmax <-
  4724. function (..., na.rm = FALSE) 
  4725. {
  4726.         elts <- list(...)
  4727.         maxmm <- as.vector(elts[[1]])
  4728.         for (each in elts[-1]) {
  4729.             work <- cbind(maxmm, as.vector(each)) 
  4730.             nas <- is.na(work)
  4731.             work[,1][nas[,1]] <- work[,2][nas[,1]]
  4732.             work[,2][nas[,2]] <- work[,1][nas[,2]]
  4733.             change <- work[,1] < work[,2]
  4734.             work[,1][change] <- work[,2][change]
  4735.             if (!na.rm) work[,1][nas[,1]+nas[,2] > 0] <- NA
  4736.             maxmm <- work[,1]
  4737.         }
  4738.         maxmm
  4739. }
  4740. pmin <-
  4741. function (..., na.rm = FALSE)
  4742. {
  4743.         elts <- list(...)
  4744.         minmm <- as.vector(elts[[1]])
  4745.         for (each in elts[-1]) {
  4746.             work <- cbind(minmm, as.vector(each))
  4747.             nas <- is.na(work)
  4748.             work[,1][nas[,1]] <- work[,2][nas[,1]]
  4749.             work[,2][nas[,2]] <- work[,1][nas[,2]]
  4750.             change <- work[,1] > work[,2]
  4751.             work[,1][change] <- work[,2][change]
  4752.             if (!na.rm) work[,1][nas[,1]+nas[,2] > 0] <- NA
  4753.             minmm <- work[,1]
  4754.         }
  4755.         minmm
  4756. }
  4757. points <- function(x, ...)
  4758. UseMethod("points")
  4759. points.default <- function(x, y=NULL, pch=1, col="black", ...) {
  4760.     plot.xy(xy.coords(x,y), type="p", pch=pch, col=col, ...)
  4761. }
  4762. polygon <-
  4763. function(x, y=NULL, border=par("fg"), ...)
  4764. {
  4765.     xy <- xy.coords(x, y)
  4766.     .Internal(polygon(xy$x, xy$y, border=border, ...))
  4767. }
  4768. postscript <- function(
  4769.     file="Rplots.ps",
  4770.     paper=options("papersize")$papersize,
  4771.     landscape=TRUE,
  4772.     width=0,
  4773.     height=0,
  4774.     family="Helvetica",
  4775.     pointsize=12,
  4776.     bg="white",
  4777.     fg="black",
  4778.     onefile,
  4779.     print.it,
  4780.     append)
  4781. {
  4782.     .Internal(device(
  4783.         "postscript",
  4784.         as.character(c(file, paper, family, bg, fg)),
  4785.         c(width, height, landscape, pointsize)))
  4786. }
  4787. ppoints <- function(x) {
  4788.     n <- length(x)
  4789.     if(n == 1) n <- x
  4790.     (1:n-0.5)/n
  4791. }
  4792. predict <- function(fit,...) UseMethod("predict")
  4793. predict.default <- function (object, ...) {
  4794.                  namelist <- list(...)
  4795.                  names(namelist) <- substitute(list(...))[-1]
  4796.                  m <- length(namelist)
  4797.                  X <- as.matrix(namelist[[1]])
  4798.                  if (m > 1) 
  4799.                    for (i in (2:m)) X <- cbind(X, namelist[[i]])
  4800.                  if (object$intercept) 
  4801.                    X <- cbind(rep(1, NROW(X)), X)
  4802.                  k <- NCOL(X)
  4803.                  if (length(object$coef) != k) 
  4804.                    stop("Wrong number of predictors")
  4805.                  predictor <- X %*% object$coef
  4806.                  ip <- real(NROW(X))
  4807.                  for (i in (1:NROW(X))) ip[i] <- sum(X[i, ] * 
  4808.                        (object$covmat %*% X[i, ]))
  4809.                  stderr1 <- sqrt(ip)
  4810.                  stderr2 <- sqrt(object$rms^2 + ip)
  4811.                  tt <- qt(0.975, object$df)
  4812.                  conf.l <- predictor - tt * stderr1
  4813.                  conf.u <- predictor + tt * stderr1
  4814.                  pred.l <- predictor - tt * stderr2
  4815.                  pred.u <- predictor + tt * stderr2
  4816.                  z <- cbind(predictor, conf.l, conf.u, pred.l, pred.u)
  4817.                  rownames(z) <- paste("P", 1:NROW(X), sep = "")
  4818.                  colnames(z) <- c("Predicted", "Conf lower", "Conf upper",
  4819.                                   "Pred lower", "Pred upper")
  4820.                  z
  4821. }
  4822. pretty <- function(x, n=5) {
  4823.     if(!is.numeric(x))
  4824.         stop("x must be numeric")
  4825.     if(is.na(n[1]) || n[1] < 1)
  4826.         stop("invalid n value")
  4827.     z <- .C("pretty",l=min(x),u=max(x),n=as.integer(n))
  4828.     seq(z$l,z$u,length=z$n+1)
  4829. }
  4830. print <- function(x, ...)
  4831. UseMethod("print")
  4832. print.default <- function(x,digits=NULL,quote=TRUE,na.print=NULL,print.gap=NULL)
  4833. {
  4834.     .Internal(print.default(x,digits,quote,na.print,print.gap))
  4835. }
  4836. print.atomic <- function(x,quote=TRUE,...) print.default(x,quote=quote)
  4837. prmatrix <- function(x, rowlab=character(0), collab=character(0), 
  4838.     quote=TRUE, right=FALSE)
  4839.     .Internal(prmatrix(x,rowlab,collab,quote,right))
  4840. print.tabular <- function(table, digits = max(3, .Options$digits - 3),
  4841.         na.print = "", ...)
  4842. {
  4843.     if(!is.null(table$title)) cat("\n", table$title, "\n\n", sep="")
  4844.     if(!is.null(table$topnote))
  4845.         cat(paste(table$topnote, collapse="\n"), "\n\n", sep="")
  4846.         print.default(table$table, digits=digits, na = "", print.gap = 2)
  4847.     if(!is.null(table$botnote)) cat("\n",
  4848.         paste(table$botnote, collapse="\n"), sep="")
  4849.         cat("\n")
  4850. }
  4851. ### -*- R -*-
  4852. prompt <- function(object, ...) UseMethod("prompt")
  4853. ## Later, we may want  a data.frame method (as S).
  4854. prompt.default <- function(object, filename = paste0(name, ".man"),
  4855.                force.function = FALSE)
  4856. {
  4857.   paste0 <- function(...) paste(..., sep = "")
  4858.   name <- substitute(object)
  4859.   if(is.language(name) && !is.name(name)) name <- eval(name)
  4860.   name <- as.character(name)
  4861.   fn <- get(name)
  4862.   ##-- 'file' will contain the "lines" to be put in the  manual file
  4863.   if(is.function(fn) || force.function) {
  4864.     argls <- formals(fn)
  4865.     n <- length(argls)
  4866.     if(n > 0) { s <- 1:n; arg.names <- names(argls)
  4867.     }      else s <- integer(0)
  4868.     file <- paste0("TITLE(", name, " @@ ~~function to do ... ~~)")
  4869.     ##-- Construct the 'call':
  4870.     call <- paste0(name, "(")
  4871.     for(i in s) {
  4872.       n.i <- arg.names[i]
  4873.       call <- paste0(call, n.i, if(n.i == "...") "" else "=",
  4874.              if(mode(argls[[i]]) == "missing") ""
  4875.                else deparse(argls[[i]]))
  4876.       if(i != n) call <- paste0(call, ", ")
  4877.     }
  4878.     file <- c(file, "USAGE(", paste0(call, ")"),
  4879.           ")", paste0("ALIAS(", name, ")"))
  4880.     if(length(s))
  4881.       file <- c(file, "ARGUMENTS(",
  4882.         paste0("ARG(", arg.names, " @@",
  4883.                " ~~Describe ", arg.names, " here~~  )"),
  4884.         ")")
  4885.     fn.def <- deparse(fn)
  4886.     if(any(br <- substr(fn.def,1,1) == ")"))
  4887.       fn.def[br] <- paste(" ", fn.def[br])
  4888.     file <- c(file,
  4889.           "DESCRIPTION(",
  4890.           "~~ a precise description of what the function does. ~~",
  4891.           ")",
  4892.           "VALUE(",
  4893.           "~Describe the value returned",
  4894.           ")",
  4895.           "~~~~~~~ For  multiple values (list), use 'VALUES' INSTEAD !",
  4896.           "             ---------------              ------",
  4897.           "VALUES(",
  4898.           "A description of the LIST of values returned.  Use",
  4899.           "@@",
  4900.           "ARG(comp1 @@ Description of `comp1')",
  4901.           "ARG(comp2 @@ Description of `comp2')",
  4902.           "...",
  4903.           ")",
  4904.           "REFERENCES(",
  4905.           "~put references to the literature / web site here,...",
  4906.           ")",
  4907.           "NOTE(",
  4908.           "~further notes~",
  4909.           ")",
  4910.           "~make other sections like WARNING with SECTION(...)~",
  4911.           "SEEALSO(", "~ functions to SEE ALSO as  LANG(LINK(~~fun~~))",
  4912.           ")",
  4913.           "EXAMPLES(",
  4914.           "##---- Should be DIRECTLY executable !! ----",
  4915.           "##-- ==>  Define data, use random,",
  4916.           "##--      or do  help(data=index)  for the standard data sets.",
  4917.           "BLANK", "## The function is currently defined as",
  4918.           fn.def,
  4919.           ")"
  4920.           ##-- not yet: , "KEYWORD( ~keyword )"
  4921.           )
  4922.   } else { #-- not function --
  4923.     file <- c("NON_FUNCTION()",
  4924.           paste("TITLE(", name, "@@ ~~data-name / kind ...  )"),
  4925.           "DESCRIPTION(",
  4926.           "~~ a precise description of what the function does. ~~",
  4927.           ")")
  4928.   }
  4929.   cat(file, file = filename, sep = "\n")
  4930.   RHOME <- system("printenv RHOME", intern = TRUE)
  4931.   if(substr(RHOME,1,8) == "/tmp_mnt") RHOME <- substr(RHOME,9,1000)
  4932.   cat("created file named ", filename, " in the current directory.\n",
  4933.       " Edit the file and move it to the appropriate directory,\n",
  4934.       paste(RHOME,"src/manual/man/",sep="/") , "dropping the ending '.man'\n"
  4935.       )
  4936.   on.exit()  # DEBUG off
  4937.   invisible(file)
  4938. }
  4939. qqnorm <- function(y, ylim, main="Normal Q-Q Plot",
  4940.     xlab="Theoretical Quantiles", ylab="Sample Quantiles", ...) {
  4941.     y <- y[!is.na(y)]
  4942.     if(missing(ylim)) ylim <- c(min(y),max(y))
  4943.     x <- (1:length(y)-0.5)/length(y)
  4944.     plot(qnorm(x), sort(y), main=main ,xlab=xlab, ylab=ylab, ylim=ylim, ...)
  4945. }
  4946. qqline <- 
  4947. function(y, ...)
  4948. {
  4949.     y <- quantile(y[!is.na(y)],c(0.25, 0.75)) 
  4950.     x <- qnorm(c(0.25, 0.75))
  4951.     slope <- diff(y)/diff(x)
  4952.     int <- y[1]-slope*x[1]
  4953.     abline(int, slope, ...)    
  4954. }
  4955. qqplot <- function(x, y, plot.it = TRUE, xlab = deparse(substitute(x)), 
  4956. ylab = deparse(substitute(y)), ...)
  4957. {
  4958.     sx<-sort(x)
  4959.     sy<-sort(y)
  4960.     lenx<-length(sx)
  4961.     leny<-length(sy)
  4962.     if( leny < lenx )
  4963.         sx<-approx(1:lenx, sx, n=leny)$y
  4964.     if( leny > lenx )
  4965.         sy<-approx(1:leny, sy, n=lenx)$y
  4966.     if(plot.it)
  4967.         plot(sx, sy, xlab = xlab, ylab = ylab, ...)
  4968.     invisible(list(x = sx, y = sy))
  4969. }
  4970. is.qr <- function(x) !is.null(x$qr)
  4971. qr <- function(x, tol= 1e-07)
  4972. {
  4973.     x <- as.matrix(x)
  4974.     p <- as.integer(ncol(x))
  4975.     n <- as.integer(nrow(x))
  4976.     if(!is.double(x))
  4977.         storage.mode(x) <- "double"
  4978.     .Fortran("dqrdc2",
  4979.         qr=x,
  4980.         n,
  4981.         n,
  4982.         p,
  4983.         as.double(tol),
  4984.         rank=integer(1),
  4985.         qraux = double(p),
  4986.         pivot = as.integer(1:p),
  4987.         double(2*p))[c(1,6,7,8)]
  4988. }
  4989. qr.coef <- function(qr, y)
  4990. {
  4991.     if( !is.qr(qr) )
  4992.         stop("first argument must be a QR decomposition")
  4993.     n <- nrow(qr$qr)
  4994.     p <- ncol(qr$qr)
  4995.     k <- as.integer(qr$rank)
  4996.     y <- as.matrix(y)
  4997.     ny <- as.integer(ncol(y))
  4998.     storage.mode(y) <- "double"
  4999.     if( nrow(y) != n )
  5000.         stop("qr and y must have the same number of rows")
  5001.     z <- .Fortran("dqrcf",
  5002.         as.double(qr$qr),
  5003.         n, k,
  5004.         as.double(qr$qraux),
  5005.         y,
  5006.         ny,
  5007.         coef=matrix(0,nr=k,nc=ny),
  5008.         info=integer(1))
  5009.     if(z$info != 0) stop("exact singularity in qr.coef")
  5010.     if(k < p) {
  5011.         coef <- matrix(as.double(NA),nr=p,nc=ny)
  5012.         coef[qr$pivot[1:k],] <- z$coef
  5013.     }
  5014.     else coef <- z$coef
  5015.     if(ncol(y) == 1)
  5016.         dim(coef) <- NULL
  5017.     return(coef)
  5018. }
  5019. qr.qy <- function(qr, y)
  5020. {
  5021.     if(!is.qr(qr)) stop("argument is not a QR decomposition")
  5022.     n <- as.integer(nrow(qr$qr))
  5023.     p <- as.integer(ncol(qr$qr))
  5024.     k <- as.integer(qr$rank)
  5025.     y <- as.matrix(y)
  5026.     ny <- as.integer(ncol(y))
  5027.     storage.mode(y) <- "double"
  5028.     if( nrow(y) != n )
  5029.         stop("qr and y must have the same number of rows")
  5030.     .Fortran("dqrqy",
  5031.         as.double(qr$qr),
  5032.         n, k,
  5033.         as.double(qr$qraux),
  5034.         y,
  5035.         ny,
  5036.         qy=mat.or.vec(n,ny))$qy
  5037. }
  5038. qr.qty <- function(qr, y)
  5039. {
  5040.     if(!is.qr(qr)) stop("argument is not a QR decomposition")
  5041.     n <- as.integer(nrow(qr$qr))
  5042.     p <- as.integer(ncol(qr$qr))
  5043.     k <- as.integer(qr$rank)
  5044.     y <- as.matrix(y)
  5045.     ny <- as.integer(ncol(y))
  5046.     storage.mode(y) <- "double"
  5047.     if( nrow(y) != n )    
  5048.         stop("qr and y must have the same number of rows")
  5049.     .Fortran("dqrqty",     
  5050.         as.double(qr$qr),
  5051.         n, k,
  5052.         as.double(qr$qraux),
  5053.         y,
  5054.         ny,
  5055.         qty=mat.or.vec(n,ny))$qty
  5056. }
  5057. qr.resid <- function(qr, y)
  5058. {
  5059.     if(!is.qr(qr)) stop("argument is not a QR decomposition")
  5060.     n <- as.integer(nrow(qr$qr))
  5061.     p <- as.integer(ncol(qr$qr))
  5062.     k <- as.integer(qr$rank)
  5063.     y <- as.matrix(y)
  5064.     ny <- as.integer(ncol(y))
  5065.     storage.mode(y) <- "double"
  5066.     if( nrow(y) != n )
  5067.         stop("qr and y must have the same number of rows")
  5068.     .Fortran("dqrrsd",
  5069.         as.double(qr$qr),
  5070.         n, k,
  5071.         as.double(qr$qraux),
  5072.         y,
  5073.         ny,
  5074.         rsd=mat.or.vec(n,ny))$rsd
  5075. }
  5076. qr.fitted <- function(qr, y, k=qr$rank)
  5077. {
  5078.     if(!is.qr(qr)) stop("argument is not a QR decomposition")
  5079.     n <- as.integer(nrow(qr$qr))
  5080.     p <- as.integer(ncol(qr$qr))
  5081.     k <- as.integer(k)
  5082.     if(k > qr$rank) stop("k is too large")
  5083.     y <- as.matrix(y)
  5084.     ny <- as.integer(ncol(y))
  5085.     storage.mode(y) <- "double"
  5086.     if( nrow(y) != n )
  5087.         stop("qr and y must have the same number of rows")
  5088.     .Fortran("dqrxb", 
  5089.         as.double(qr$qr),
  5090.         n, k,
  5091.         as.double(qr$qraux),
  5092.         y,
  5093.         ny,
  5094.         xb=mat.or.vec(n,ny))$xb
  5095. }
  5096. ## qr.solve is defined in 'solve'
  5097. quantile <- function (x, probs = seq(0, 1, 0.25), na.rm = FALSE) 
  5098. {
  5099.     if (na.rm) 
  5100.         x <- x[!is.na(x)]
  5101.     else if (any(!is.finite(x))) 
  5102.         stop("Missing values, NaN\'s and Inf\'s not allowed if na.rm=FALSE")
  5103.     n <- length(x)
  5104.     if(any(probs < 0 | probs > 1))
  5105.         stop("probs outside [0,1]")
  5106.     index <- 1 + (n - 1) * probs
  5107.     lo <- floor(index)
  5108.     hi <- ceiling(index)
  5109.     x <- sort(x, partial=unique(c(lo,hi)))
  5110.     qs <- x[lo] + (x[hi] - x[lo]) * (index - lo)  
  5111.     names(qs) <- paste(round(100*probs), "%", sep="")
  5112.     qs
  5113. }
  5114. quit <- function(save = "ask")
  5115. .Internal(quit(save))
  5116. q<-quit
  5117. range <- function(..., na.rm=FALSE)
  5118. c(min(..., na.rm=na.rm),max(..., na.rm=na.rm))
  5119. "count.fields" <-
  5120. function(file, sep = "", skip = 0)
  5121. {
  5122.     .Internal(count.fields(file, sep, skip))
  5123. }
  5124. "read.table" <-
  5125. function (file, header=FALSE, sep="", row.names, col.names, as.is=FALSE,
  5126.     na.strings="NA", skip=0)
  5127. {
  5128.     type.convert <-
  5129.     function(x, na.strings="NA", as.is=FALSE)
  5130.         .Internal(type.convert(x, na.strings, as.is))
  5131.         #  basic column counting and header determination
  5132.         #  we record whether it looks like we column names
  5133.         #  rlabp == 1
  5134.     row.lens <- count.fields(file, sep, skip)
  5135.     nlines <- length(row.lens)
  5136.     rlabp <- 0
  5137.     if (nlines > 1 && (row.lens[2] - row.lens[1]) == 1) {
  5138.         if (missing(header))
  5139.             header <- TRUE
  5140.         rlabp <- 1
  5141.     }
  5142.         # read in the header
  5143.     if (header) {
  5144.         col.names <- scan(file, what="", sep=sep, nlines=1, quiet=TRUE, skip=skip)
  5145.         skip <- skip + 1
  5146.         row.lens <- row.lens[-1]
  5147.         nlines <- nlines - 1
  5148.     }
  5149.     else if (missing(col.names))
  5150.         col.names <- paste("V", 1:row.lens[1], sep="")
  5151.         #  check that all rows have equal lengths
  5152.     cols <- unique(row.lens)
  5153.     if (length(cols) != 1)
  5154.         stop("all rows must have the same length",
  5155.             paste(row.lens, sep=","))
  5156.         #  set up for the scan of the file
  5157.         #  we read all values as character strings
  5158.         #  and convert later.
  5159.     what <- rep(list(""), cols)
  5160.     if (rlabp == 1)
  5161.         col.names <- c("row.names", col.names)
  5162.     names(what) <- col.names
  5163.     data <- scan(file=file, what=what, sep=sep, n=nlines*cols, skip=skip,
  5164.             na.strings=na.strings, quiet=TRUE)
  5165.         #  ok, now we have the data
  5166.         #  we now we convert to numeric or factor variables
  5167.         #  (depending on the specifies value of "as.is")
  5168.         #  we do this here so that columns match up
  5169.     cols <- length(data)
  5170.     if(is.logical(as.is)) {
  5171.         as.is <- rep(as.is, length=cols)
  5172.     }
  5173.     else if(is.numeric(as.is)) {
  5174.         if(any(as.is < 1 | as.is > cols))
  5175.             stop("invalid numeric as.is expression")
  5176.         i <- rep(FALSE, cols)
  5177.         i[as.is] <- TRUE
  5178.         as.is <- i
  5179.     }
  5180.     if (length(as.is) != cols)
  5181.         stop("as.is has the wrong length")
  5182.     for (i in 1:cols) {
  5183.         if (!as.is[i])
  5184.             data[[i]] <- type.convert(data[[i]], na.strings = na.strings)
  5185.     }
  5186.         #  now we determine row names
  5187.     if (missing(row.names)) {
  5188.         if (rlabp == 1) {
  5189.             row.names <- data[[1]]
  5190.             data <- data[-1]
  5191.         }
  5192.         else row.names <- as.character(1:nlines)
  5193.     }
  5194.     else if (is.null(row.names))
  5195.         row.names <- as.character(1:nlines)
  5196.     else if (is.character(row.names)) {
  5197.         if (length(row.names) == 1) {
  5198.             rowvar <- (1:cols)[match(col.names, row.names, 0) == 1]
  5199.             row.names <- data[[rowvar]]
  5200.             data <- data[-rowvar]
  5201.         }
  5202.     }
  5203.     else if (is.numeric(row.names) && length(row.names) == 1) {
  5204.         rlabp <- row.names
  5205.         row.names <- data[[rlabp]]
  5206.         data <- data[-rlabp]
  5207.     }
  5208.     else stop("invalid row.names specification")
  5209.         #  this is extremely underhanded
  5210.         #  we should use the constructor function ...
  5211.         #  don't try this at home kids
  5212.     class(data) <- "data.frame"
  5213.     row.names(data) <- row.names
  5214.     return(data)
  5215. }
  5216. rect <- function(xleft, ybottom, xright, ytop, col=NULL, border=par("fg"), lty=NULL, xpd=FALSE) {
  5217.     .Internal(rect(
  5218.         as.double(xleft),
  5219.         as.double(ybottom),
  5220.         as.double(xright),
  5221.         as.double(ytop),
  5222.         col=col,
  5223.         border=border,
  5224.         lty=lty,
  5225.         xpd=xpd))
  5226. }
  5227. rm <- function(...,list=character(0), envir=NULL,inherits=FALSE) {
  5228.     names<- as.character(substitute(list(...)))[-1]
  5229.     list<-c(list,names)
  5230.     .Internal(remove(list,envir,inherits))
  5231. }
  5232. rep <- function(x, times, length.out)
  5233. {
  5234.     if (length(x) == 0)
  5235.         return(x)
  5236.     if (missing(times))
  5237.         times <- ceiling(length.out/length(x))
  5238.     r<-.Internal(rep(x,times))
  5239.     if (!missing(length.out))
  5240.         return(r[1:length.out])
  5241.     return(r)
  5242. }
  5243. replace <-
  5244. function (x, list, values) 
  5245. {
  5246.         x[list] <- values
  5247.         x
  5248. }
  5249. require <-
  5250. function (name, quietly = FALSE) 
  5251. {
  5252.     if (missing(name)) 
  5253.         return(TRUE)    
  5254.     if (!exists(".Libraries", inherits = TRUE))
  5255.         assign(".Libraries", character(0), NULL)
  5256.     if (!exists(".Provided", inherits=TRUE))
  5257.         assign(".Provided", character(0), NULL)
  5258.     name <- substitute(name)
  5259.     if (!is.character(name)) 
  5260.         name <- deparse(name)
  5261.     if (is.na(match(name, .Libraries))&& is.na(match(name, .Provided))) {
  5262.         file <- system.file("library", name)
  5263.         if (file == "") {
  5264.             if (!quietly) 
  5265.     warning(paste("Required library ", name, " not found.\n"))
  5266.             return(FALSE)
  5267.         }
  5268.         if (!quietly) 
  5269.             cat("Autoloading required library:", name, "\n")
  5270.         sys.source(file)
  5271.         assign(".Libraries", c(name, .Libraries), NULL)
  5272.     }
  5273.     return(TRUE)
  5274. }
  5275. provide <-
  5276. function(name)
  5277. {
  5278.     if (!exists(".Libraries", inherits = TRUE)) 
  5279.         assign(".Libraries", character(0), NULL)
  5280.     if (!exists(".Provided",inherits=TRUE))
  5281.         assign(".Provided", character(0), NULL)
  5282.     if (missing(name))
  5283.         return(list(provide=.Provided, library=.Libraries))
  5284.     name<-substitute(name)
  5285.     if (!is.character(name))
  5286.         name<-deparse(name)
  5287.     if (is.na(match(name, .Libraries)) && is.na(match(name, .Provided))){
  5288.         assign(".Provided",c(name,.Provided),NULL)
  5289.         return(TRUE)
  5290.     } 
  5291.     else 
  5292.         return(FALSE)
  5293. }
  5294. rev <- function(x) x[length(x):1]
  5295. rm <- function(...,list=character(0), envir=NULL,inherits=FALSE) {
  5296.     names<- as.character(substitute(list(...)))[-1]
  5297.     list<-c(list,names)
  5298.     .Internal(remove(list,envir,inherits))
  5299. }
  5300. rownames <- function(x) {
  5301.     dn <- dimnames(x)
  5302.     if(is.null(dn)) dn else dn[[1]]
  5303. }
  5304. "rownames<-" <- function(x, value) {
  5305.     dn <- dimnames(x)
  5306.     if(is.null(dn)) dimnames(x) <- list(value, dn)
  5307.     else dimnames(x) <- list(value, dn[[2]])
  5308.     x
  5309. }
  5310. sample <- function(x, size, replace=FALSE)
  5311. {
  5312.     if(length(x) == 1 && x >= 1) {
  5313.         if(missing(size)) size <- x
  5314.         .Internal(sample(x, size, replace))
  5315.     }
  5316.     else {
  5317.         if(missing(size)) size <- length(x)
  5318.         x[.Internal(sample(length(x), size, replace))]
  5319.     }
  5320. }
  5321. sapply <- function(X, FUN, ..., simplify = TRUE)
  5322. {
  5323.   if(is.character(FUN))
  5324.     FUN <- get(FUN, mode = "function")
  5325.     else if(mode(FUN) != "function") {
  5326.       farg <- substitute(FUN)
  5327.       if(mode(farg) == "name")
  5328.     FUN <- get(farg, mode = "function")
  5329.     else stop(paste("\"", farg, "\" is not a function", sep = ""))
  5330.     }
  5331.   answer <- lapply(as.list(X), FUN, ...)
  5332.   if(simplify && length(answer) &&
  5333.      length(common.len <- unique(unlist(lapply(answer, length)))) == 1) {
  5334.     if(common.len == 1)
  5335.       unlist(answer, recursive = FALSE)
  5336.     else if(common.len > 1)
  5337.       array(unlist(answer, recursive = FALSE),
  5338.         c(common.len, length(X)), list(NULL, names(answer)))
  5339.     else answer
  5340.   } else answer
  5341. }
  5342. scan <- function(file="", what=0, nmax=-1, sep="", skip=0, nlines=0,
  5343.     na.strings="NA", flush=FALSE, strip.white=FALSE, quiet=FALSE) {
  5344.     if( !missing(sep) )
  5345.         na.strings<-c(na.strings,"")
  5346.     .Internal(scan(file, what, nmax, sep, skip, nlines, na.strings,flush,strip.white, quiet))
  5347. }
  5348. sd <- function(x, na.rm=FALSE) sqrt(var(x, na.rm=na.rm))
  5349. segments <- function(x0, y0, x1, y1, col=par("fg"), lty=par("lty"))
  5350.     .Internal(segments(x0, y0, x1, y1, col=col, lty=lty))
  5351. seq <- function(from = 1, to = 1, by = ((to - from)/(length.out - 1)), length.out = NULL, along.with = NULL) {
  5352.     if(!missing(along.with))
  5353.         length.out <- length(along.with)
  5354.     else if(!missing(length.out))
  5355.         length.out <- ceiling(length.out)
  5356.     if(nargs() == 1 && !missing(from)) {
  5357.         if(mode(from) == "numeric" && length(from) == 1)
  5358.             1:from
  5359.         else seq(along.with = from)
  5360.     }
  5361.     else if(is.null(length.out))
  5362.         if(missing(by))
  5363.             from:to
  5364.         else {
  5365.             n <- (to - from)/by
  5366.             if(n < 0)
  5367.                 stop("Wrong sign in by= argument")
  5368.             from + (0:n) * by
  5369.         }
  5370.     else if(length.out < 0)
  5371.         stop("Length cannot be negative")
  5372.     else if(length.out == 0)
  5373.         numeric(0)
  5374.     else if(missing(by)) {
  5375.         if(from == to || length.out < 2)
  5376.             by <- 1
  5377.         if(missing(to))
  5378.             to <- from + length.out - 1
  5379.         if(missing(from))
  5380.             from <- to - length.out + 1
  5381.         if(length.out > 2)
  5382.             if(from == to)
  5383.                 rep(from, length.out)
  5384.             else as.vector(c(from, from + (1:(length.out - 2)) *
  5385.                     by, to))
  5386.         else as.vector(c(from, to))[1:length.out]
  5387.     }
  5388.     else if(missing(to))
  5389.         from + (0:(length.out - 1)) * by
  5390.     else if(missing(from))
  5391.         to - ((length.out - 1):0) * by
  5392.     else stop("Too many arguments")
  5393. }
  5394. sequence <- function(nvec)
  5395. {
  5396.     sequence <- NULL
  5397.     for(i in nvec) sequence<-c(sequence,seq(1:i))
  5398.     return(sequence)
  5399. }
  5400. qr.solve <- function(a,b, tol = 1e-7)
  5401. {
  5402.     if( !is.qr(a) )
  5403.         a <- qr(a, tol = tol)
  5404.     nc <- ncol(a$qr)
  5405.     if( a$rank != nc )
  5406.         stop("singular matrix 'a' in solve")
  5407.     if( missing(b) ) {
  5408.         if( nc != nrow(a$qr) )
  5409.             stop("only square matrices can be inverted")
  5410.         b<-diag(1,nc)
  5411.     }
  5412.     b<-as.matrix(b)
  5413.     return(qr.coef(a,b))
  5414. }
  5415. solve.qr <- qr.solve
  5416. solve <- qr.solve
  5417. sort <- function(x, partial=NULL, na.last=NA) {
  5418.     nas <- x[is.na(x)]
  5419.     x <- x[!is.na(x)]
  5420.     if(!is.null(partial))
  5421.         y <- .Internal(psort(x, partial))
  5422.     else {
  5423.         nms <- names(x)
  5424.         if(!is.null(nms)) {
  5425.             o <- order(x)
  5426.             y <- x[o]
  5427.             names(y) <- nms[o]
  5428.         }
  5429.         else
  5430.             y <- .Internal(sort(x))
  5431.     }
  5432.     if(!is.na(na.last)) {
  5433.         if(!na.last) y <- c(nas, y)
  5434.         else if (na.last) y <- c(y, nas)
  5435.     }
  5436.     y
  5437. }
  5438. source <- function (file, local=FALSE) {
  5439.     if(local) envir <- sys.frame(sys.parent())
  5440.     else if(!local) envir <- .GlobalEnv
  5441.     exprs <- parse(n = -1, file = file)
  5442.     if (length(exprs) == 0) return(invisible())
  5443.     for (i in exprs) {
  5444.         yy <- eval(i, envir)
  5445.     }
  5446.     invisible(yy)
  5447. }
  5448. sys.source <- function (file) {
  5449.     exprs <- parse(n = -1, file = file)
  5450.     if (length(exprs) == 0) return(invisible())
  5451.     for (i in exprs) {
  5452.         yy <- eval(i, NULL)
  5453.     }
  5454.     invisible(yy)
  5455. }
  5456. spline <- function(x, y, n=3*length(x), method="fmm", xmin=min(x), xmax=max(x)) {
  5457.     method <- match(method, c("periodic", "natural", "fmm"))
  5458.     if(is.na(method))
  5459.         stop("invalid interpolation method")
  5460.     if(length(x) != length(y))
  5461.         stop("x and y lengths differ in spline")
  5462.     if( !is.numeric(x) || !is.numeric(y) )
  5463.         stop("spline: x and y must be numeric")
  5464.     if(any(diff(x) <= 0))
  5465.         stop("invalid x array in spline")
  5466.     if(method == 1 && y[1] != y[length(y)]) {
  5467.         warning("first and last y values differ in spline - using y[1] for both")
  5468.         y[length(y)] <- y[1]
  5469.     }
  5470.     z <- .C("spline_coef",
  5471.         method=as.integer(method),
  5472.         n=length(x),
  5473.         x=as.double(x),
  5474.         y=as.double(y),
  5475.         b=double(length(x)),
  5476.         c=double(length(x)),
  5477.         d=double(length(x)),
  5478.         e=if(method == 1) double(length(x)) else double(0))
  5479.     u <- seq(xmin, xmax, length.out=n)
  5480.     .C("spline_eval",
  5481.         z$method,
  5482.         length(u),
  5483.         x=u,
  5484.         y=double(n),
  5485.         z$n,
  5486.         z$x,
  5487.         z$y,
  5488.         z$b,
  5489.         z$c,
  5490.         z$d)[3:4]
  5491. }
  5492. splinefun <- function(x, y, method="fmm") {
  5493.     method <- match(method, c("periodic", "natural", "fmm"))
  5494.     if(is.na(method))
  5495.         stop("invalid interpolation method")
  5496.     if(length(x) != length(y))
  5497.         stop("x and y lengths differ in spline")
  5498.     if( !is.numeric(x) || !is.numeric(y) )
  5499.         stop("splinefun: both x and y must be numeric")
  5500.     if(any(diff(x) <= 0))
  5501.         stop("invalid x array in spline")
  5502.     if(method == 1 && y[1] != y[length(y)]) {
  5503.         warning("first and last y values differ in spline - using y[1] for both")
  5504.         y[length(y)] <- y[1]
  5505.     }
  5506.     z <- .C("spline_coef",
  5507.         method=as.integer(method),
  5508.         n=length(x),
  5509.         x=as.double(x),
  5510.         y=as.double(y),
  5511.         b=double(length(x)),
  5512.         c=double(length(x)),
  5513.         d=double(length(x)),
  5514.         e=if(method == 1) double(length(x)) else double(0))
  5515.     rm(x,y,method)
  5516.     function(x) {
  5517.         .C("spline_eval",
  5518.             z$method,
  5519.             length(x),
  5520.             x=as.double(x),
  5521.             y=double(length(x)),
  5522.             z$n,
  5523.             z$x,
  5524.             z$y,
  5525.             z$b,
  5526.             z$c,
  5527.             z$d)$y
  5528.     }
  5529. }
  5530. split <- function(x, f) .Internal(split(x, as.factor(f)))
  5531. stem <- function(x,scale=1, width=80, atom=0.00000001) {
  5532.     if( !is.numeric(x) )
  5533.         stop("stem: x must be numeric")
  5534.     x <- x[!is.na(x)]
  5535.     if(length(x)==0) stop("no non-missing values")
  5536.     .C("stemleaf", as.double(x), length(x), as.double(scale), as.integer(width), as.double(atom))
  5537.     invisible(NULL)
  5538. }
  5539. # Dotplots a la Box, Hunter and Hunter
  5540. stripplot <- function(x, method="overplot", jitter=0.1, offset=1/3,
  5541.         vertical=FALSE, group.names,
  5542.         xlim, ylim, main="", ylab="", xlab="",
  5543.         pch=0, col=par("fg"), cex=par("cex"))
  5544. {
  5545.     method <- pmatch(method, c("overplot", "jitter", "stack"))[1]
  5546.     if(is.na(method) || method==0)
  5547.         error("invalid plotting method")
  5548.     if(is.language(x)) {
  5549.         if(length(x) == 3 && deparse(x[[1]]) == '~') {
  5550.             groups <- eval(x[[3]], sys.frame(sys.parent())) 
  5551.             x <- eval(x[[2]], sys.frame(sys.parent()))
  5552.             groups <- split(x, groups)
  5553.         }
  5554.         else stop("invalid first argument")
  5555.     }
  5556.     else if(is.list(x)) {
  5557.         groups <- x
  5558.     }
  5559.     else if(is.numeric(x)) {
  5560.         groups <- list(x)
  5561.     }
  5562.     n <- length(groups)
  5563.     if(!missing(group.names)) attr(groups, "names") <- group.names
  5564.     else if(is.null(attr(groups, "names"))) attr(groups, "names") <- 1:n
  5565.     dlim <- rep(NA, 2)
  5566.     for(i in groups)
  5567.         dlim <- range(dlim, i, na.rm=T)
  5568.     glim <- c(1, n)
  5569.     if(method == 2) {
  5570.         if(n == 1) glim <- glim + c(-5, 5) * jitter
  5571.         else glim <- glim + c(-2, 2) * jitter
  5572.     }
  5573.     if(method == 3) {
  5574.         if(n == 1) glim <- glim + c(-1,1)
  5575.         else glim <- glim + c(0, 0.5)
  5576.     }
  5577.     if(missing(xlim)) {
  5578.         if(vertical) xlim <- glim
  5579.         else xlim <- dlim
  5580.     }
  5581.     if(missing(ylim)) {
  5582.         if(vertical) ylim <- dlim
  5583.         else ylim <- glim
  5584.     }
  5585.     plot(xlim, ylim, type="n", ann=FALSE, axes=FALSE)
  5586.     box()
  5587.     if(vertical) {
  5588.         if(n > 1) axis(1, at=1:n, lab=names(groups))
  5589.         axis(2)
  5590.     }
  5591.     else {
  5592.         axis(1)
  5593.         if(n > 1) axis(2, at=1:n, lab=names(groups))
  5594.     }
  5595.     if(vertical) csize <- cex*xinch(par("cin")[1])
  5596.     else csize <- cex*yinch(par("cin")[2])
  5597.     f <- function(x) seq(length(x))
  5598.     for(i in 1:length(groups)) {
  5599.         x <- groups[[i]]
  5600.         y <- rep(i,length(x))
  5601.         if(method == 2) y <- y + runif(length(y), -jitter, jitter)
  5602.         if(method == 3) {
  5603.             xg <- split(x, factor(x))
  5604.             xo <- lapply(xg, f)
  5605.             x <- unlist(xg)
  5606.             y <- y + (unlist(xo) - 1) * offset * csize
  5607.         }
  5608.         if(vertical) points(y, x, col=col[(i - 1)%%length(col) + 1],
  5609.             pch=pch[(i - 1)%%length(pch) + 1], cex=cex)
  5610.         else points(x, y, col=col[(i - 1)%%length(col) + 1],
  5611.             pch=pch[(i - 1)%%length(pch) + 1], cex=cex)
  5612.     }
  5613.     title(main=main, xlab=xlab, ylab=ylab)
  5614. }
  5615. "structure" <-
  5616. function (.Data, ...)
  5617. {
  5618.     specials <- c(".Dim", ".Dimnames", ".Names", ".Tsp", ".Label")
  5619.     replace <- c("dim", "dimnames", "names", "tsp", "levels")
  5620.     attrib <- list(...)
  5621.     if(!is.null(attrib)) {
  5622.         m <- match(names(attrib), specials)
  5623.         ok <- (!is.na(m) & m > 0)
  5624.         names(attrib)[ok] <- replace[m[ok]]
  5625.         if(any(names(attrib) == "tsp"))
  5626.             attrib$class <- unique(c("ts", attrib$class))
  5627.         if(is.numeric(.Data) && any(names(attrib) == "levels"))
  5628.             .Data <- factor(.Data)
  5629.         attributes(.Data) <- c(attributes(.Data), attrib)
  5630.     }
  5631.     return(.Data)
  5632. }
  5633. strwidth <- function(s, units="user", cex=NULL)
  5634.     .Internal(strwidth(s, pmatch(units, c("user", "figure", "inches")), cex))
  5635. sum <- function(..., na.rm=FALSE) 
  5636. .Internal(sum(...,na.rm=na.rm))
  5637. min <- function(..., na.rm=FALSE) 
  5638. .Internal(min(...,na.rm=na.rm))
  5639. max <- function(..., na.rm=FALSE) 
  5640. .Internal(max(...,na.rm=na.rm))
  5641. prod <- function(...,na.rm=FALSE)
  5642. .Internal(prod(...,na.rm=na.rm))
  5643. summary <-
  5644. function (x, ...)
  5645.     UseMethod("summary")
  5646. summary.default <-
  5647. function(object, ..., digits = max(options()$digits - 3, 3))
  5648. {
  5649.     if(is.factor(object))
  5650.         return(summary.factor(object, ...))
  5651.     else if(is.matrix(object))
  5652.         return(summary.matrix(object, ...))
  5653.     value <- if(is.numeric(object)) {
  5654.         nas <- is.na(object)
  5655.         object <- object[!nas]
  5656.         qq <- quantile(object)
  5657.         qq <- signif(c(qq[1:3], mean(object), qq[4:5]), digits)
  5658.         names(qq) <- c("Min.", "1st Qu.", "Median", "Mean", "3rd Qu.", "Max.")
  5659.         if(any(nas))
  5660.             c(qq, "NA's" = sum(nas))
  5661.         else qq
  5662.     } else if(is.recursive(object) && !is.language(object) &&
  5663.         (n <- length(object))) {
  5664.         sumry <- array("", c(n, 3), list(names(object),
  5665.             c("Length", "Class", "Mode")))
  5666.         ll <- numeric(n)
  5667.         for(i in 1:n) {
  5668.             ii <- object[[i]]
  5669.             ll[i] <- length(ii)
  5670.             sumry[i, 2] <- if(is.object(ii)) class(ii) else "-none-"
  5671.             sumry[i, 3] <- mode(ii)
  5672.         }
  5673.         sumry[, 1] <- format(as.integer(ll))
  5674.         class(sumry) <- "table"
  5675.         sumry
  5676.     }
  5677.     else c(Length = length(object), Class = class(object), Mode = mode(object))
  5678.     class(value) <- "table"
  5679.     value
  5680. }
  5681. summary.factor <-
  5682. function(x, maxsum = 100, ...)
  5683. {
  5684.     nas <- is.na(x)
  5685.     ll <- levels(x)
  5686.     if(any(nas)) maxsum <- maxsum - 1
  5687.     tbl <- table(x)
  5688.     tt <- c(tbl) # names dropped ...
  5689.     names(tt) <- dimnames(tbl)[[1]]
  5690.     if(length(ll) > maxsum) {
  5691.         drop <- maxsum:length(ll)
  5692.         o <- rev(order(tt))
  5693.         tt <- c(tt[o[ - drop]], "(Other)" = sum(tt[o[drop]]))
  5694.     }
  5695.     if(any(nas)) c(tt, "NA's" = sum(nas)) else tt
  5696. }
  5697. summary.matrix <-
  5698. function(x, ...)
  5699.     summary.data.frame(data.frame(x))
  5700. summary.data.frame <-
  5701. function(x, maxsum = 7, ...)
  5702. {
  5703.     z <- lapply(as.list(x), summary, maxsum = maxsum)
  5704.     nv <- length(x)
  5705.     nm <- names(x)
  5706.     lw <- numeric(nv)
  5707.     nr <- max(unlist(lapply(z, length)))
  5708.     for(i in 1:nv) {
  5709.         sms <- z[[i]]
  5710.         lbs <- format(names(sms))
  5711.         sms <- paste(lbs, ":", format(sms), "  ", sep = "")
  5712.         lw[i] <- nchar(lbs[1])
  5713.         length(sms) <- nr
  5714.         z[[i]] <- sms
  5715.     }
  5716.     z <- unlist(z, use.names=FALSE)
  5717.     dim(z) <- c(nr, nv)
  5718.      blanks <- paste(character(max(lw) + 2), collapse = " ")
  5719.      pad <- floor(lw-nchar(nm)/2)
  5720.      nm <- paste(substring(blanks, 1, pad), nm, sep = "")
  5721.      dimnames(z) <- list(rep("", nr), nm)
  5722.     attr(z, "class") <- c("table") #, "matrix")
  5723.     z
  5724. }
  5725. print.table <-
  5726. function(x, digits= .Options$digits, quote = FALSE, na.print='', ...)
  5727. {
  5728.  print.default(unclass(x), digits=digits, quote=quote, na.print=na.print, ...)
  5729. }
  5730. svd <- function(x, nu=min(n,p), nv=min(n,p)) {
  5731.     if(!is.numeric(x))
  5732.         stop("argument to svd must be numeric")
  5733.     x <- as.matrix(x)
  5734.     dx <- dim(x)
  5735.     n <- dx[1]
  5736.     p <- dx[2]
  5737.     if(nu == 0) {
  5738.         job <- 0
  5739.         u <- double(0)
  5740.     }
  5741.     else if(nu == n) {
  5742.         job <- 10
  5743.         u <- matrix(0, n, n)
  5744.     }
  5745.     else if(nu == p) {
  5746.         job <- 20
  5747.         u <- matrix(0, n, p)
  5748.     }
  5749.     else
  5750.         stop("nu must be 0, nrow(x) or ncol(x)")
  5751.     if(nv == 0)
  5752.         job <- job + 0
  5753.     else if(nv == p || nv == n)
  5754.         job <- job + 1
  5755.     else
  5756.         stop("nv must be 0 or ncol(x)")
  5757.     if(job == 0)
  5758.         v <- double(0)
  5759.     else
  5760.         v <- matrix(0, p, p)
  5761.     mn <- min(n,p)
  5762.     mm <- min(n+1,p)
  5763.     z <- .Fortran("dsvdc",
  5764.         x,
  5765.         n,
  5766.         n,
  5767.         p,
  5768.         d=double(mm),
  5769.         double(p),
  5770.         u=u,
  5771.         n,
  5772.         v=v,
  5773.         p,
  5774.         double(n),
  5775.         as.integer(job),
  5776.         info=integer(1),
  5777.         DUP=FALSE)[c("d","u","v","info")]
  5778.     if(z$info)
  5779.         stop(paste("error ",z$info," in dsvdc"))
  5780.     z$d <- z$d[1:mn]
  5781.     if(nv && nv < p) z$v <- z$v[, 1:nv]
  5782.     z[c("d", if(nu) "u" else NULL, if(nv) "v" else NULL)]
  5783. }
  5784. sweep <-
  5785. function(x, MARGIN, STATS, FUN = "-", ...)
  5786. {
  5787.     if(is.character(FUN))
  5788.         FUN <- get(FUN)
  5789.     dims <- dim(x)
  5790.     perm <- c(MARGIN, (1:length(dims))[ - MARGIN])
  5791.     FUN(x, aperm(array(STATS, dims[perm]), order(perm)), ...)
  5792. }
  5793. switch <- function(EXPR,...)
  5794.     .Internal(switch(EXPR,...))
  5795. sys.call <-function(which=0)
  5796.  .Internal(sys.call(which))
  5797. sys.calls <-function()
  5798.  .Internal(sys.calls())
  5799. sys.frame <-function(which=0)
  5800.  .Internal(sys.frame(which))
  5801. sys.function <-function(which=0)
  5802.  .Internal(sys.function(which))
  5803. sys.frames <-function()
  5804.  .Internal(sys.frames())
  5805. sys.nframe <- function()
  5806.  .Internal(sys.nframe())
  5807. sys.parent <- function(n = 1)
  5808.  .Internal(sys.parent(n))
  5809. sys.parents <- function()
  5810.  .Internal(sys.parents())
  5811. sys.status <- function()
  5812.  list(sys.calls=sys.calls(), sys.parents=sys.parents(), sys.frames=sys.frames())
  5813. sys.on.exit <- function()
  5814.  .Internal(sys.on.exit())
  5815. system <- function(call, intern=FALSE) 
  5816.     .Internal(system(call,intern))
  5817. system.file <- function(dir, name)
  5818. {
  5819.     system(paste("$RHOME/cmd/filename", dir, name), intern=TRUE)
  5820. }
  5821. table <- function(x, ...)
  5822. {
  5823.     if (nargs() == 0)
  5824.         stop("no arguments")
  5825.     bin <- 0
  5826.     lens <- NULL
  5827.     dims <- integer(0)
  5828.     pd <- 1
  5829.     dn <- NULL
  5830.     if(nargs() == 1 && is.list(x))
  5831.         args <- x
  5832.     else
  5833.         args <- list(x, ...)
  5834.     for (a in args) {
  5835.         if (is.null(lens))
  5836.             lens <- length(a)
  5837.         if (length(a) != lens)
  5838.             stop("all arguments must have the same length")
  5839.         if (!is.factor(a))
  5840.             cat <- as.factor(a)
  5841.         else cat <- a
  5842.         l <- levels(cat)
  5843.         dims <- c(dims, nlevels(cat))
  5844.         dn <- c(dn, list(l))
  5845.         bin <- bin + pd * (as.integer(cat) - 1)
  5846.         pd <- pd * nlevels(cat)
  5847.     }
  5848.     bin <- bin[!is.na(bin)]
  5849.     array(tabulate(bin + 1, pd), dims, dimnames = dn)
  5850. }
  5851. tabulate <- function(bin, nbins = max(bin))
  5852. {
  5853.     if(!is.numeric(bin) && !is.factor(bin))
  5854.         stop("tabulate: bin must be numeric or a factor")
  5855.     if((n <- length(bin)) == 0) bin <- 1
  5856.     else bin <- as.integer(bin)
  5857.     .C("tabulate",
  5858.         ans = integer(nbins),
  5859.         bin,
  5860.         n)$ans
  5861. }
  5862. tapply <- function (x, INDEX, FUN, ...) 
  5863. {
  5864.     if (is.character(FUN)) 
  5865.         FUN <- get(FUN, mode = "function")
  5866.     if (mode(FUN) != "function") 
  5867.         stop(paste("\"", FUN, "\" is not a function"))
  5868.     if (!is.list(INDEX)) INDEX <- list(INDEX)
  5869.     namelist <- vector("list", length(INDEX))
  5870.     extent <- integer(length(INDEX))
  5871.     nx <- length(x)
  5872.     group <- rep(1, nx)
  5873.     ngroup <- 1
  5874.     for (i in seq(INDEX)) {
  5875.         index <- as.factor(INDEX[[i]])
  5876.         if (length(index) != nx) 
  5877.             stop("arguments must have same length")
  5878.         namelist[[i]] <- levels(index)
  5879.         extent[[i]] <- nlevels(index)
  5880.         group <- group + ngroup * (codes(index) - 1)
  5881.         ngroup <- ngroup * nlevels(index)
  5882.     }
  5883.     if (missing(FUN)) return(group)
  5884.     ans <- lapply(split(x, group), FUN, ...) 
  5885.     if(all(unlist(lapply(ans,length))==1))
  5886.         ans <- unlist(ans, recursive=FALSE)
  5887.     if(length(INDEX) == 1) {
  5888.         names(ans) <- namelist[[1]]
  5889.     }
  5890.     else {
  5891.         dim(ans) <- extent
  5892.         dimnames(ans) <- namelist
  5893.     }
  5894.     return(ans)
  5895. }
  5896. text <- function(x, y=NULL, text, ...)
  5897.     .Internal(text(xy.coords(x,y), as.character(text), ...))
  5898. title <- function(main=NULL, sub=NULL, xlab=NULL, ylab=NULL, ...)
  5899.     .Internal(title(
  5900.         as.character(main),
  5901.         as.character(sub),
  5902.         as.character(xlab),
  5903.         as.character(ylab),
  5904.         ...
  5905.     ))
  5906. traceback <- function() as.character(.Traceback)
  5907. trunc <- function(x) ifelse(x<0,ceiling(x),floor(x))
  5908. start <-
  5909. function(x, ...)
  5910. UseMethod("start")
  5911. end <-
  5912. function(x, ...)
  5913. UseMethod("end")
  5914. frequency <-
  5915. function(x, ...)
  5916. UseMethod("frequency")
  5917. time <-
  5918. function(x, ...)
  5919. UseMethod("time")
  5920. window <-
  5921. function(x, ...)
  5922. UseMethod("window")
  5923. ts <-
  5924. function(data=NA, start=1, end=numeric(0), frequency=1, deltat=1)
  5925. {
  5926.     ts.eps <- .Options$ts.eps
  5927.     if(is.null(ts.eps)) ts.eps <- 1.e-6
  5928.     if(is.matrix(data)) {
  5929.         nseries <- ncol(data)
  5930.         ndata <- nrow(data)
  5931.     }
  5932.     else {
  5933.         nseries <- 1
  5934.         ndata <- length(data)
  5935.     }
  5936.     if(missing(frequency)) frequency <- 1/deltat
  5937.     if(missing(deltat)) deltat <- 1/deltat
  5938.     if(frequency > 1 && abs(frequency - round(frequency)) < ts.eps)
  5939.         frequency <- round(frequency)
  5940.     if(length(start) > 1) {
  5941.         if(start[2] > frequency) stop("invalid start")
  5942.         start <- start[1] + (start[2] - 1)/frequency
  5943.     }
  5944.     if(length(end) > 1) {
  5945.         if(end[2] > frequency) stop("invalid end")
  5946.         end <- end[1] + (end[2] - 1)/frequency
  5947.     }
  5948.     if(missing(end))
  5949.         end <- start + (ndata - 1)/frequency
  5950.     else if(missing(start))
  5951.         start <- end - (ndata - 1)/frequency
  5952.     nobs <- floor((end - start) * frequency + 1.01)
  5953.     if(nseries == 1) {
  5954.         if(ndata < nobs)
  5955.             data <- rep(data, length=nobs)
  5956.         else if(nobs > ndata)
  5957.             data <- data[1:nobs]
  5958.     }
  5959.     else {
  5960.         if(ndata < nobs)
  5961.             data <- data[rep(1:ndata, length=nobs)]
  5962.         else if(nobs > ndata)
  5963.             data <- data[1:nobs,]
  5964.     }
  5965.     attr(data, "tsp") <- c(start, end, frequency)
  5966.     attr(data, "class") <- "ts"
  5967.     data
  5968. }
  5969. tsp <-
  5970. function(x)
  5971.     attr(x, "tsp")
  5972. "tsp<-" <-
  5973. function(x, tsp)
  5974. {
  5975.     attr(x,"tsp") <- tsp
  5976.     class(x) <- "ts"
  5977.     x
  5978. }
  5979. is.ts <-
  5980. function (x) 
  5981. inherits(x, "ts")
  5982. as.ts <-
  5983. function (x) 
  5984. if (is.ts(x)) x else ts(x)
  5985. start.ts <-
  5986. function(x)
  5987. {
  5988.     ts.eps <- .Options$ts.eps
  5989.     if(is.null(ts.eps)) ts.eps <- 1.e-6
  5990.     tsp <- attr(as.ts(x), "tsp")
  5991.     is <- tsp[1]*tsp[3]
  5992.     if(abs(is-round(is)) < ts.eps) {
  5993.         is <- floor(tsp[1])
  5994.         fs <- floor(tsp[3]*(tsp[1] - is)+0.001)
  5995.         c(is,fs+1)
  5996.     }
  5997.     else ts[1]
  5998. }
  5999. end.ts <-
  6000. function(x)
  6001. {
  6002.     ts.eps <- .Options$ts.eps
  6003.     if(is.null(ts.eps)) ts.eps <- 1.e-6
  6004.     tsp <- attr(as.ts(x), "tsp")
  6005.     is <- tsp[2]*tsp[3]
  6006.     if(abs(is-round(is)) < ts.eps) {
  6007.         is <- floor(tsp[2])
  6008.         fs <- floor(tsp[3]*(tsp[2] - is)+0.001)
  6009.         c(is, fs+1)
  6010.     }
  6011.     else ts[2]
  6012. }
  6013. frequency.ts <-
  6014. function(x)
  6015. {
  6016.     tsp <- attr(as.ts(x), "tsp")
  6017.     tsp[3]
  6018. }
  6019. time.ts <-
  6020. function (x) 
  6021. {
  6022.     x <- as.ts(x)
  6023.     if(is.matrix(x)) n <- nrow(x)
  6024.     else n <- length(x)
  6025.     xtsp <- attr(x, "tsp")
  6026.     ts(seq(xtsp[1], xtsp[2], length=n),
  6027.         start=start(x), end=end(x), frequency=frequency(x))
  6028. }
  6029. print.ts <- function(x, calender, ...)
  6030. {
  6031.     if(missing(calender))
  6032.         calender <- any(frequency(x)==c(4,12))
  6033.     if(all(frequency(x) != c(1,4,12)))
  6034.         calender <- FALSE
  6035.     if(!is.matrix(x) && calender) {
  6036.         if(frequency(x) == 12) {
  6037.             start.pad <- start(x)[2] - 1
  6038.             end.pad <- 12 - end(x)[2]
  6039.             data <- matrix(c(rep(NA, start.pad), x,
  6040.                 rep(NA, end.pad)), nc=12, byrow=T)
  6041.             dimnames(data) <- list(
  6042.                 as.character(start(x)[1]:end(x)[1]),
  6043.                 month.abb)
  6044.         }
  6045.         else if(frequency(x) == 4) {
  6046.             start.pad <- start(x)[2] - 1
  6047.             end.pad <- 4 - end(x)[2]
  6048.             data <- matrix(c(rep(NA, start.pad), x,
  6049.                 rep(NA, end.pad)), nc=4, byrow=T)
  6050.             dimnames(data) <- list(
  6051.                     paste(start(x)[1]:end(x)[1], ":" , sep=""),
  6052.                     c("Qtr1", "Qtr2", "Qtr3", "Qtr4"))
  6053.         }
  6054.         else if(frequency(x) == 1) {
  6055.             data <- x
  6056.             attributes(data) <- NULL
  6057.             names(data) <- time(x)
  6058.         }
  6059.     }
  6060.     else  {
  6061.         cat("Time-Series:\nStart =", deparse(start(x)),
  6062.             "\nEnd =", deparse(end(x)),
  6063.             "\nFrequency =", deparse(frequency(x)), "\n")
  6064.         data <- x
  6065.         attr(data, "tsp") <- NULL
  6066.         attr(data, "class") <- NULL
  6067.         # something like this is needed here
  6068.         # if(is.matrix(x)) rownames(data) <- time(x)
  6069.     }
  6070.     print(data, ...)
  6071.     invisible(x)
  6072. }
  6073. plot.ts <-
  6074. function (x, type="l", xlim, ylim, xlab, ylab, log="",
  6075.     col=par("col"), bg=NA, pch=par("pch"), lty=par("lty"), ...)
  6076. {
  6077.     time.x <- time(x)
  6078.     if(missing(xlim)) xlim <- range(time.x)
  6079.     if(missing(ylim)) ylim <- range(x, na.rm=TRUE)
  6080.     if(missing(xlab)) xlab <- "Time"
  6081.     if(missing(ylab)) ylab <- deparse(substitute(x))
  6082.     plot.new()
  6083.     plot.window(xlim, ylim, log)
  6084.     if(is.matrix(x)) {
  6085.         for(i in 1:ncol(x))
  6086.             lines.default(time.x, x[,i],
  6087.                 col=col[(i-1)%%length(col) + 1],
  6088.                 lty=lty[(i-1)%%length(lty) + 1],
  6089.                 bg=bg[(i-1)%%length(bg) + 1],
  6090.                 pch=pch[(i-1)%%length(pch) + 1],
  6091.                 type=type)
  6092.     }
  6093.     else {
  6094.         lines.default(time.x, x, col=col[1], bg=bg, lty=lty[1],
  6095.             pch=pch[1], type=type)
  6096.     }
  6097.     title(xlab=xlab, ylab=ylab, ...)
  6098.     axis(1, ...)
  6099.     axis(2, ...)
  6100.     box(...)
  6101. }
  6102. window.ts <-
  6103. function(x, start, end)
  6104. {
  6105.     x <- as.ts(x)
  6106.     xtsp <- tsp(x)
  6107.     freq <- xtsp[3]
  6108.     xtime <- time(x)
  6109.     ts.eps <- .Options$ts.eps
  6110.         if (is.null(ts.eps)) 
  6111.                 ts.eps <- 1e-06
  6112.     if(missing(start))
  6113.         start <- xtsp[1]
  6114.     else start <- switch(length(start),
  6115.             start,
  6116.             start[1] + (start[2] - 1)/freq,
  6117.             stop("Bad value for start"))
  6118.     if(start < xtsp[1]) {
  6119.         start <- xtsp[1]
  6120.         warning("start value not changed")
  6121.     }
  6122.     if(missing(end))
  6123.         end <- xtsp[2]
  6124.     else end <- switch(length(end),
  6125.             end,
  6126.             end[1] + (end[2] - 1)/freq,
  6127.             stop("Bad value for end"))
  6128.     if(end > xtsp[2]) {
  6129.         end <- xtsp[2]
  6130.         warning("end value not changed")
  6131.     }
  6132.     if(start > end)
  6133.         stop("start cannot be after end")
  6134.     if(all(abs(start - xtime) > abs(start) * ts.eps)) {
  6135.         start <- xtime[(xtime > start) & ((start + 1/freq) > xtime)]
  6136.     }
  6137.     if(all(abs(end - xtime) > abs(end) * ts.eps)) {
  6138.         end <- xtime[(xtime < end) & ((end - 1/freq) < xtime)]
  6139.     }
  6140.     if(is.matrix(x))
  6141.         x <- x[(trunc((start - xtsp[1]) * freq + 1.5):trunc((end - 
  6142.             xtsp[1]) * freq + 1.5)), , drop = F]
  6143.     else x <- x[trunc((start - xtsp[1]) * freq + 1.5):trunc((end - xtsp[1])
  6144.             * freq + 1.5)]
  6145.     tsp(x) <- c(start, end, freq)
  6146.     x
  6147. }
  6148. "[.ts" <-
  6149. function(x, i, j)
  6150. {
  6151.     y <- NextMethod("[")
  6152.     if(is.matrix(x) & missing(i))
  6153.         ts(y, start=start(x), freq=frequency(x))
  6154.     else y
  6155. }
  6156. t.test <- function(x, y=NULL, alternative="two.sided",mu=0, paired = FALSE, var.equal = FALSE,  conf.level = 0.95) {
  6157.     choices<-c("two.sided","greater","less")
  6158.     alt<- pmatch(alternative,choices)
  6159.     alternative<-choices[alt]
  6160.     if( length(alternative)>1 || is.na(alternative) )
  6161.         stop("alternative must be one \"greater\", \"less\", \"two.sided\"")
  6162.     if( !missing(mu) ) 
  6163.         if( length(mu) != 1  || is.na(mu) )
  6164.             stop("mu must be a single number")
  6165.     if( !missing(conf.level) )
  6166.         if( length(conf.level) !=1 || is.na(conf.level) || conf.level<0 || conf.level > 1)
  6167.             stop("conf.level must be a number between 0 and 1")
  6168.     if( !is.null(y) ) {
  6169.         dname<-paste(deparse(substitute(x)),"and",paste(deparse(substitute(y))))
  6170.         if(paired) 
  6171.             xok<-yok<-complete.cases(x,y)
  6172.         else {
  6173.             yok<-!is.na(y)
  6174.             xok<-!is.na(x)
  6175.         }
  6176.         y<-y[yok]
  6177.     }
  6178.     else {
  6179.         dname<-deparse(substitute(x))
  6180.         if( paired ) stop("y is missing for paired test")
  6181.         xok<-!is.na(x)
  6182.         yok<-NULL
  6183.     }
  6184.     x<-x[xok]
  6185.     if( paired ) {
  6186.         x<- x-y
  6187.         y<- NULL
  6188.     }
  6189.     nx <- length(x)
  6190.     if(nx <= 2) stop("not enough x observations")
  6191.     mx <- mean(x)
  6192.     vx <- var(x)
  6193.     estimate<-mx
  6194.     if(is.null(y)) {
  6195.         df <- length(x)-1
  6196.         stderr<-sqrt(vx/nx)
  6197.         tstat <- (mx-mu)/stderr
  6198.         method<-ifelse(paired,"Paired t-test","One Sample t-test")
  6199.         names(estimate)<-ifelse(paired,"mean of the differences","mean of x")
  6200.     } else {
  6201.         ny <- length(y)
  6202.         if(ny <= 2) stop("not enough y observations")
  6203.         my <- mean(y)
  6204.         vy <- var(y)
  6205.         method<-ifelse(var.equal,"Two Sample t-test","Welch Two Sample t-test")
  6206.         estimate<-c(mx,my)
  6207.         names(estimate)<-c("mean of x","mean of y")
  6208.         if(var.equal) { 
  6209.             df <- nx+ny-2
  6210.             v <- ((nx-1)*vx + (ny-1)*vy)/df
  6211.             stderr <- sqrt(v*(1/nx+1/ny))
  6212.             tstat <- (mx-my-mu)/stderr
  6213.         } else {
  6214.             stderrx <-sqrt(vx/nx)
  6215.             stderry <-sqrt(vy/ny)
  6216.             stderr <- sqrt(stderrx^2 + stderry^2)
  6217.             df <- stderr^4/(stderrx^4/(nx-1) + stderry^4/(ny-1))
  6218.             tstat <- (mx - my - mu)/stderr
  6219.         }
  6220.     }
  6221.     if (alternative == "less") {
  6222.         pval <- pt(tstat, df)
  6223.         cint <- c(NA, tstat * stderr + qt(conf.level, df) * stderr)
  6224.     }
  6225.     else if (alternative == "greater") {
  6226.         pval <- 1 - pt(tstat, df)
  6227.         cint <- c(tstat * stderr - qt(conf.level, df) * stderr, NA)
  6228.     }
  6229.     else {
  6230.         pval <- 2 * pt(-abs(tstat), df)
  6231.         alpha <- 1 - conf.level
  6232.         cint <- c(tstat * stderr - qt((1 - alpha/2), df) * stderr,
  6233.             tstat * stderr + qt((1 - alpha/2), df) * stderr)
  6234.     }
  6235.     names(tstat)<-"t"
  6236.     names(df)<-"df"
  6237.     if(paired || !is.null(y) ) 
  6238.         names(mu)<-"difference in means"
  6239.     else
  6240.         names(mu)<- "mean"
  6241.     attr(cint,"conf.level")<-conf.level
  6242.     rval<-list(statistic = tstat, parameter = df, p.value = pval, 
  6243. conf.int=cint, estimate=estimate, null.value = mu, alternative=alternative,
  6244. method=method, data.name=dname)
  6245.     attr(rval,"class")<-"htest"
  6246.     return(rval)
  6247. }
  6248. cm <- function(x) 2.54*x
  6249. xinch <- function(x=1)
  6250.     x * diff(par("usr")[1:2])/par("pin")[1]
  6251. yinch <- function(x=1)
  6252.     x * diff(par("usr")[3:4])/par("pin")[2]
  6253. unix.time <- function(expr)
  6254. {
  6255.   ## Purpose: Return CPU (and other) times that 'expr' used ..
  6256.   ##    Modelled after S`s  "unix.time"; to be used with R (rel. 0.4 & later)
  6257.   ## -------------------------------------------------------------------------
  6258.   ## Arguments: expr: 'any' valid R expression
  6259.   ## -------------------------------------------------------------------------
  6260.   if(!exists("proc.time", mode = "function", inherits=TRUE))
  6261.     stop(paste("proc.time  must be enabled at configuration / compile time\n",
  6262.            "    [add '-DProctime' to SYSTEM in src/Systems/<YOURSYS>]"))
  6263.   loc.frame <- sys.parent(1)
  6264. ##-S   if(loc.frame == 1)
  6265. ##-S    loc.frame <- F
  6266.   on.exit(cat("Timing stopped at:", proc.time() - time, "\n"))
  6267.   expr <- substitute(expr)
  6268.   time <- proc.time()
  6269.   eval(expr, envir = loc.frame) #<-- 'R'
  6270.   new.time <- proc.time()
  6271.   on.exit()
  6272.   if(length(new.time) == 3)    new.time <- c(new.time, 0, 0)
  6273.   if(length(time) == 3)        time     <- c(time, 0, 0)
  6274.   new.time - time
  6275. }
  6276. upper.tri <- function(x, diag = FALSE)
  6277. {
  6278.     x <- as.matrix(x)
  6279.         if(diag) row(x) <= col(x)
  6280.         else row(x) < col(x)
  6281. }
  6282. mat.or.vec <- function(nr,nc) 
  6283.         if(nc==1) numeric(nr) else matrix(0,nr,nc)
  6284. var <- function(x, y=x, na.rm = FALSE) {
  6285.     if(is.matrix(x) || !missing(y)) cov(x,y)
  6286.     else {
  6287.         if (na.rm) x <- x[!is.na(x)]
  6288.         sum((x - mean(x))^2)/(length(x) - 1)
  6289.         }
  6290. }
  6291. logical <- function(n=0) vector("logical",n)
  6292. integer <- function(n=0) vector("integer",n)
  6293. real <- function(n=0) vector("real", n)
  6294. double <- function(n=0) vector("real", n)
  6295. numeric <- double
  6296. complex <- function(n=0, real=numeric(), imag=numeric())
  6297. .Internal(complex(n, real, imag))
  6298. character <- function(n=0) vector("character",n)
  6299. which <- function(x) {
  6300.     if(is.logical(x)) seq(x)[x]
  6301.     else stop("argument to \"which\" is not logical")
  6302. }
  6303. windows<- function() .Internal(device("Win32","",c(0,0,0)))
  6304. write <- function(x, file="data",ncolumns=if(is.character(x)) 1 else 5, append=FALSE)
  6305.         cat(x, file=file, sep=c(rep(" ",ncolumns-1), "\n"), append=append)
  6306. x11 <-
  6307. function(display="", width=7, height=7, ps=12,
  6308.     printcmd=options("printcmd")$printcmd,
  6309.     paper=options("papersize")$papersize,
  6310.     orientation="flexible")
  6311. {
  6312.     if(is.na(match(paper, c("none", "a4", "letter"))))
  6313.         stop("unsupported paper size in x11")
  6314.     orientation <- match(orientation,c("portrait", "landscape", "flexible"))
  6315.     if(is.na(orientation))
  6316.         stop("unknown page orientation in x11")
  6317.     .Internal(
  6318.         device("X11",
  6319.         as.character(c(display[1], paper)),
  6320.         as.double(c(width, height, ps, orientation))))
  6321. }
  6322.