Description Usage Arguments Value Note Author(s) Examples
Efficient C implementation of the sample covariance estimator. The denominator is defined as the sample size.
1 | weightedCovarRcppN(x, y, w)
|
x |
Covariate without weighting (numeric vector). |
y |
Response. The mean of the response contains weights (numeric vector). |
w |
Weights for averaging (numeric vector). |
Weighted variance (numeric scalar).
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 16 17 | # Simulate two random vectors
set.seed(3975)
x <- rnorm(100)
set.seed(-3975)
y <- rnorm(100)
# Calculate variance with standard R function
# Rescaling ensures that both calculations use same denominator "n"
covarEst <- cov(x, y) * (100-1) / 100
# Calculate weighted variance with equal weights
equalW <- rep(1, 100)
weightCovarEst <- weightedCovarRcppN(x=x, y=y, w=equalW)
# Output comparison
all.equal(covarEst, weightCovarEst)
# Runtime comparison
library(microbenchmark)
microbenchmark(Default=cov(x, y), New=weightedCovarRcpp(x=x, y=y, 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.