weightedCovarRcpp: Estimate weighted covariance

Description Usage Arguments Value Note Author(s) Examples

Description

Efficient C implementation of the sample covariance estimator. The denominator is defined as the sum of all weights.

Usage

1

Arguments

x

Covariate without weighting (numeric vector).

y

Response. The mean of the response contains weights (numeric vector).

w

Weights for averaging (numeric vector).

Value

Weighted variance (numeric scalar).

Note

If all weights are set to 1, the denominator is identical to n. There are no safety checks of input arguments.

Author(s)

Thomas Welchowski

Examples

 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 <- weightedCovarRcpp(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

carSurv documentation built on May 1, 2019, 8:44 p.m.