Sweep Out Array Summaries

DESCRIPTION:
Returns an array like the input A with STATS "swept" out.

USAGE:
sweep(A, MARGIN, STATS, FUN="-", ...)

REQUIRED ARGUMENTS:
A:
array. Missing values (NAs) are allowed.
MARGIN:
vector describing the dimensions of A that correspond to STATS.
STATS:
vector giving a summary statistic of array A that is to be swept out. Missing values (NAs) are allowed.

OPTIONAL ARGUMENTS:
FUN:
function or character string naming a function to be used in the sweep operation.
...:
additional arguments to FUN, if any.

VALUE:
an array like A, but with marginal statistics swept out as defined by the other arguments.

DETAILS:
The handling of missing values is determined by FUN.

In the most common cases, FUN is "-" or "/" to subtract or divide by statistics that result from using the apply function on the array. For example: colmean <- apply(z,2,mean) computes column means of array z. zcenter <- sweep(z,2,colmean) removes the column means.

More generally, based on MARGIN, there are one or more values of A that would be used by apply to create STATS. sweep creates an array like A where the corresponding value of STATS is used in place of each value of A that would have been used to create STATS. The function FUN is then used to operate element-by-element on each value in A and in the constructed array.


BUGS:
When FUN is a generic function, f, that calls .Internal instead of UseMethod (e.g., dim, +, or as.vector) sweep will not find the correct method for it (it will use the default method). In those cases it is best to replace FUN=f by FUN=function(x,...)f(x,...). For example, replace FUN="+" by FUN=function(e1,e2)e1+e2 and replace FUN=dim by FUN=function(x)dim(x). This applies to any function that takes another function as an argument, not just to sweep.

SEE ALSO:
apply , scale .

EXAMPLES:
a <- sweep(a,2,apply(a,2,mean)) # subtract col means
a <- sweep(a,1,apply(a,1,mean)) # subtract row means
     # a simple two-way analysis