mean2 | R Documentation |
Computes the sample mean of all or a subset of values.
mean2(x, idxs = NULL, na.rm = FALSE, refine = TRUE, ...)
x |
An NxK |
idxs |
A |
na.rm |
If |
refine |
If |
... |
Not used. |
mean2(x, idxs)
gives equivalent results as mean(x[idxs])
,
but is faster and more memory efficient since it avoids the actual
subsetting which requires copying of elements and garbage collection
thereof.
If x
is numeric
and refine = TRUE
, then a
two-pass scan is used to calculate the average. The first scan calculates
the total sum and divides by the number of (non-missing) values. In the
second scan, this average is refined by adding the residuals towards the
first average. The mean
() uses this approach.
mean2(..., refine = FALSE)
is almost twice as fast as
mean2(..., refine = TRUE)
.
Returns a numeric
scalar.
Henrik Bengtsson
mean
().
To efficiently sum over a subset, see sum2
().
x <- 1:10
n <- length(x)
idxs <- seq(from = 1, to = n, by = 2)
s1 <- mean(x[idxs]) # 25
s2 <- mean2(x, idxs = idxs) # 25
stopifnot(identical(s1, s2))
idxs <- seq(from = n, to = 1, by = -2)
s1 <- mean(x[idxs]) # 25
s2 <- mean2(x, idxs = idxs) # 25
stopifnot(identical(s1, s2))
s1 <- mean(x) # 55
s2 <- mean2(x) # 55
stopifnot(identical(s1, s2))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.