A with
STATS swept out.
sweep(A, MARGIN, STATS, FUN="-", ...)
NAs) are allowed.
A that correspond to
STATS.
A that is to be
swept out. Missing values (
NAs) are allowed.
FUN, if any.
A, but with marginal statistics swept out as
defined by the other arguments.
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.
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.
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