--- R-devel_2007-08-06/src/library/base/R/sweep.R 2007-07-27 17:51:13.000000000 +0200 +++ R-devel_2007-08-06-sweep/src/library/base/R/sweep.R 2007-08-07 10:30:12.383672960 +0200 @@ -14,10 +14,29 @@ # A copy of the GNU General Public License is available at # http://www.r-project.org/Licenses/ -sweep <- function(x, MARGIN, STATS, FUN = "-", ...) +sweep <- function(x, MARGIN, STATS, FUN = "-", check.margin=TRUE, ...) { FUN <- match.fun(FUN) dims <- dim(x) + if (check.margin) { + dimmargin <- dims[MARGIN] + dimstats <- dim(STATS) + lstats <- length(STATS) + if (lstats > prod(dimmargin)) { + warning("length of STATS greater than the extent of dim(x)[MARGIN]") + } else if (is.null(dimstats)) { # STATS is a vector + cumDim <- c(1, cumprod(dimmargin)) + upper <- min(cumDim[cumDim >= lstats]) + lower <- max(cumDim[cumDim <= lstats]) + if (upper %% lstats != 0 || lstats %% lower != 0) + warning("STATS does not recycle exactly across MARGIN") + } else { + dimmargin <- dimmargin[dimmargin > 1] + dimstats <- dimstats[dimstats > 1] + if (length(dimstats) != length(dimmargin) || any(dimstats != dimmargin)) + warning("length(STATS) or dim(STATS) do not match dim(x)[MARGIN]") + } + } perm <- c(MARGIN, (1:length(dims))[ - MARGIN]) FUN(x, aperm(array(STATS, dims[perm]), order(perm)), ...) } --- R-devel_2007-08-06/src/library/base/man/sweep.Rd 2007-07-27 17:51:35.000000000 +0200 +++ R-devel_2007-08-06-sweep/src/library/base/man/sweep.Rd 2007-08-07 10:29:45.517757200 +0200 @@ -11,7 +11,7 @@ statistic. } \usage{ -sweep(x, MARGIN, STATS, FUN="-", \dots) +sweep(x, MARGIN, STATS, FUN="-", check.margin=TRUE, \dots) } \arguments{ \item{x}{an array.} @@ -22,8 +22,18 @@ case of binary operators such as \code{"/"} etc., the function name must backquoted or quoted. (\code{FUN} is found by a call to \code{\link{match.fun}}.)} + \item{check.margin}{logical. If \code{TRUE} (the default), warn if the + length or dimensions of \code{STATS} do + not match the specified dimensions of \code{x}.} \item{\dots}{optional arguments to \code{FUN}.} } +\details{ + The consistency check among \code{STATS}, \code{MARGIN} and \code{x} + is stricter if \code{STATS} is an array than if it is a vector. + In the vector case, some kinds of recycling are allowed without a + warning. Use \code{sweep(x,MARGIN,as.array(STATS))} if \code{STATS} + is a vector and you want to be warned if any recycling occurs. +} \value{ An array with the same shape as \code{x}, but with the summary statistics swept out.