YazminRios
YazminRios

Reputation: 389

Population Variance in r

How can I calculate the population variance of my data using R?

I read there is a package called popvar but I have the Version 0.99.892 and I don't find the package

Upvotes: 24

Views: 37010

Answers (5)

kurtkim
kurtkim

Reputation: 155

This is a too-late comment, however, I want to note that a population variance can be obtained with a population mean. I don't think that a given dataset is a population.

Upvotes: 0

tzabal
tzabal

Reputation: 451

You can calculate the population variance with the following function:

pvar <- function(x) {
  sum((x - mean(x))**2) / length(x)
}

where x is a numeric vector that keeps the data of your population. For example:

> x <- c(1, 3, 5, 7, 14)
> pvar(x)
[1] 20

Upvotes: 2

PatrickT
PatrickT

Reputation: 10510

You already have a great answer, but I'd like to show that you can easily make your own convenience functions. It is surprising that a population variance/standard deviation function is not available in base R. It is available in Excel/Calc and other software. It wouldn't be difficult to have such a function. It could be named sdp or sd.p or be invoked with sd(x, pop = TRUE)

Here is a basic version of population variance with no type-checking:

  x <- 1:10
  varp <- function(x) mean((x-mean(x))^2)
  varp(x)
  ## [1] 8.25

To scale up, if speed is an issue, colSums and/or colMeans may be used (see: https://rdrr.io/r/base/colSums.html)

Upvotes: 9

akuiper
akuiper

Reputation: 214927

The var() function in base R calculate the sample variance, and the population variance differs with the sample variance by a factor of n / n - 1. So an alternative to calculate population variance will be var(myVector) * (n - 1) / n where n is the length of the vector, here is an example:

x <- 1:10
var(x) * 9 /10
[1] 8.25

From the definition of population variance:

sum((x - mean(x))^2) / 10
[1] 8.25 

Upvotes: 34

Mekki MacAulay
Mekki MacAulay

Reputation: 1727

You can find the details on package popvar here: https://cran.r-project.org/web/packages/PopVar/index.html - You can install it using the command install.packages("PopVar"); Note that the name is case sensitive (capital P, capital V).

Upvotes: 2

Related Questions