# wtd.var: Weighted Variance and Standard Deviation In npreg: Nonparametric Regression via Smoothing Splines

 wtd.var R Documentation

## Weighted Variance and Standard Deviation

### Description

Generic function for calculating weighted variance or standard deviation of a vector.

### Usage

```wtd.var(x, weights, na.rm = FALSE)

wtd.sd(x, weights, na.rm = FALSE)
```

### Arguments

 `x` Numerical or logical vector. `weights` Vector of non-negative weights. `na.rm` Logical indicating whether `NA` values should be removed before calculation.

### Details

The weighted variance is defined as

`(n / (n - 1)) * sum(weights * (x - xbar)^2) / sum(weights)`

where `n` is the number of observations with non-zero weights, and `xbar` is the weighted mean computed via the `wtd.mean` function.

The weighted standard deviation is the square root of the weighted variance.

### Value

Returns the weighted variance or standard deviation.

### Note

If `weights` are missing, the weights are defined to be a vector of ones (which is the same as the unweighted variance or standard deviation).

### Author(s)

Nathaniel E. Helwig <helwig@umn.edu>

`wtd.mean` for weighted mean calculations

`wtd.quantile` for weighted quantile calculations

### Examples

```# generate data and weights
set.seed(1)
x <- rnorm(10)
w <- rpois(10, lambda = 10)

# weighted mean
xbar <- wtd.mean(x, w)

# weighted variance
wtd.var(x, w)
(10 / 9) * sum(w * (x - xbar)^2) / sum(w)

# weighted standard deviation
wtd.sd(x, w)
sqrt((10 / 9) * sum(w * (x - xbar)^2) / sum(w))

```

npreg documentation built on July 21, 2022, 1:06 a.m.