weightedMean | R Documentation |
Computes the weighted sample mean of a numeric vector.
weightedMean(x, w = NULL, idxs = NULL, na.rm = FALSE, refine = FALSE,
...)
x |
An NxK |
w |
a vector of weights the same length as |
idxs |
A |
na.rm |
If |
refine |
If |
... |
Not used. |
Returns a numeric
scalar. If x
is of
zero length, then NaN
is returned, which is consistent with
mean
().
This function handles missing values consistently with
weighted.mean
. More precisely, if na.rm = FALSE
,
then any missing values in either x
or w
will give result
NA_real_
. If na.rm = TRUE
, then all (x, w)
data points
for which x
is missing are skipped. Note that if both x
and
w
are missing for a data points, then it is also skipped (by the same
rule). However, if only w
is missing, then the final results will
always be NA_real_
regardless of na.rm
.
Henrik Bengtsson
mean
() and weighted.mean
.
x <- 1:10
n <- length(x)
w <- rep(1, times = n)
m0 <- weighted.mean(x, w)
m1 <- weightedMean(x, w)
stopifnot(identical(m1, m0))
# Pull the mean towards zero
w[1] <- 5
m0 <- weighted.mean(x, w)
m1 <- weightedMean(x, w)
stopifnot(identical(m1, m0))
# Put even more weight on the zero
w[1] <- 8.5
m0 <- weighted.mean(x, w)
m1 <- weightedMean(x, w)
stopifnot(identical(m1, m0))
# All weight on the first value
w[1] <- Inf
m0 <- weighted.mean(x, w)
m1 <- weightedMean(x, w)
stopifnot(identical(m1, m0))
# All weight on the last value
w[1] <- 1
w[n] <- Inf
m0 <- weighted.mean(x, w)
m1 <- weightedMean(x, w)
stopifnot(identical(m1, m0))
# All weights set to zero
w <- rep(0, times = n)
m0 <- weighted.mean(x, w)
m1 <- weightedMean(x, w)
stopifnot(identical(m1, m0))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.