Re: [R] sweep() and recycling

From: Robin Hankin <>
Date: Tue 21 Jun 2005 - 21:16:58 EST

On Jun 20, 2005, at 04:58 pm, Prof Brian Ripley wrote:

> The issue here is that the equivalent command array(1:5, c(6,6)) (to 
> matrix(1:5,6,6)) gives no warning, and sweep uses array().
> I am not sure either should: fractional recycling was normally allowed 
> in S3 (S4 tightened up a bit).
> Perhaps someone who thinks sweep() should warn could contribute a 
> tested patch?

OK, modified R code and Rd file below (is this the best way to do this?)

"sweep" <-

   function (x, MARGIN, STATS, FUN = "-", give.warning = FALSE, ...) {

   FUN <-
   dims <- dim(x)
   if(give.warning & length(STATS)>1 & any(dims[MARGIN] != dim(as.array(STATS)))){

     warning("array extents do not recycle exactly")    }
   perm <- c(MARGIN, (1:length(dims))[-MARGIN])    FUN(x, aperm(array(STATS, dims[perm]), order(perm)), ...) }

\title{Sweep out Array Summaries}

   Return an array obtained from an input array by sweeping out a summary    statistic.

sweep(x, MARGIN, STATS, FUN="-", give.warning = FALSE, \dots) }

   \item{x}{an array.}
   \item{MARGIN}{a vector of indices giving the extents of \code{x}      which correspond to \code{STATS}.}
   \item{STATS}{the summary statistic which is to be swept out.}    \item{FUN}{the function to be used to carry out the sweep. In the

     case of binary operators such as \code{"/"} etc., the function name
     must be quoted.}

   \item{give.warning}{Boolean, with default \code{FALSE} meaning to    give no warning, even if array extents do not match. If    \code{TRUE}, check for the correct dimensions and if a    mismatch is detected, give a suitable warning.}    \item{\dots}{optional arguments to \code{FUN}.} }

   An array with the same shape as \code{x}, but with the summary    statistics swept out.

   If \code{STATS} is of length 1, recycling is carried out with no    warning irrespective of the value of \code{give.warning}. }


   Becker, R. A., Chambers, J. M. and Wilks, A. R. (1988)    \emph{The New S Language}.
   Wadsworth \& Brooks/Cole.

   \code{\link{apply}} on which \code{sweep} used to be based;    \code{\link{scale}} for centering and scaling. }

require(stats) # for median

med.att <- apply(attitude, 2, median)
sweep(data.matrix(attitude), 2, med.att)# subtract the column medians

a <- array(0, c(2, 3, 4))
b <- matrix(1:8, c(2, 4))
sweep(a, c(1, 3), b, "+", give.warning = TRUE) # no warning: all(dim(a)[c(1,3)] == dim(b))
sweep(a, c(1, 2), b, "+", give.warning = TRUE) # warning given


Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton
European Way, Southampton SO14 3ZH, UK
  tel  023-8059-7743

______________________________________________ mailing list
PLEASE do read the posting guide!
Received on Tue Jun 21 21:28:09 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:32:55 EST