Description Usage Arguments Value Note Author(s) Examples
Efficient C implementation of the sample variance estimator. The denominator is defined as sum of all weights.
1 | weightedVarRcpp(y, w)
|
y |
Response. The mean of the response contains weights (numeric vector). |
w |
Weights for averaging (numeric vector). |
Weighted variance (numeric scalar).
If all weights are set to 1, the denominator is identical to n. There are no safety checks of input arguments.
Thomas Welchowski
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | # Simulate a random vector
set.seed(3975)
x <- rnorm(100)
# Calculate variance with standard implementation
# Rescaling ensures that both calculations use same denominator "n"
varEst <- var(x) * (100-1) / 100
# Calculate weighted variance with equal weights
equalW <- rep(1/100, 100)
weightVarEst <- weightedVarRcpp(y=x, w=equalW)
# Output comparison
all.equal(varEst, weightVarEst)
# Runtime comparison
library(microbenchmark)
microbenchmark(Default=var(x), New=weightedVarRcppN(y=x, w=equalW), times=25)
# -> New method is multiple times faster
|
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.