How to Calculate Variance in R

You can use the var function to calculate the sample variance in R. This is part of the base R package, so you don’t need to load additional libraries.

# calculate variance in R

> test <- c(41,34,39,34,34,32,37,32,43,43,24,32)
> var(test)
[1] 30.26515

A common problem with sample data in R is missing values. As the code below indicates, missing values will cause the calculation to crash. You can use the na.rm option contained within the var function to remove missing values. It will calculate the variance using the non-missing values.

# calculate variance in R - missing values example
> test <- c(41,34,39,34,34,32,37,32,43,43,24,32, NA,NA)

# calculate variance in R - test fails due to NA values
> var(test)
[1] NA

# calculate variance in R; remove missing values, correct result
> var(test, na.rm=TRUE)
[1] 30.26515

Got other items in that problem set? Check out the standard deviation and standard error pages….

Related Materials