sweep {base} | R Documentation |

## Sweep out Array Summaries

### Description

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

### Usage

```
sweep(x, MARGIN, STATS, FUN = "-", check.margin = TRUE, ...)
```

### Arguments

`x` |
an array, including a matrix. |

`MARGIN` |
a vector of indices giving the extent(s) of |

`STATS` |
the summary statistic which is to be swept out. |

`FUN` |
the function to be used to carry out the sweep. |

`check.margin` |
logical. If |

`...` |
optional arguments to |

### Details

`FUN`

is found by a call to `match.fun`

. As in the
default, binary operators can be supplied if quoted or backquoted.

`FUN`

should be a function of two arguments: it will be called
with arguments `x`

and an array of the same dimensions generated
from `STATS`

by `aperm`

.

The consistency check among `STATS`

, `MARGIN`

and `x`

is stricter if `STATS`

is an array than if it is a vector.
In the vector case, some kinds of recycling are allowed without a
warning. Use `sweep(x, MARGIN, as.array(STATS))`

if `STATS`

is a vector and you want to be warned if any recycling occurs.

### Value

An array with the same shape as `x`

, but with the summary
statistics swept out.

### References

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

### See Also

`apply`

on which `sweep`

used to be based;
`scale`

for centering and scaling.

### Examples

```
require(stats) # for median
med.att <- apply(attitude, 2, median)
sweep(data.matrix(attitude), 2, med.att) # subtract the column medians
## More sweeping:
A <- array(1:24, dim = 4:2)
## no warnings in normal use
sweep(A, 1, 5)
(A.min <- apply(A, 1, min)) # == 1:4
sweep(A, 1, A.min)
sweep(A, 1:2, apply(A, 1:2, median))
## warnings when mismatch
sweep(A, 1, 1:3) # STATS does not recycle
sweep(A, 1, 6:1) # STATS is longer
## exact recycling:
sweep(A, 1, 1:2) # no warning
sweep(A, 1, as.array(1:2)) # warning
## Using named dimnames
dimnames(A) <- list(fee=1:4, fie=1:3, fum=1:2)
mn_fum_fie <- apply(A, c("fum", "fie"), mean)
mn_fum_fie
sweep(A, c("fum", "fie"), mn_fum_fie)
```

*base*version 4.4.0 Index]