var()

var(x, y = NULL, na.rm = FALSE, use)
Returns: numeric · Updated March 13, 2026 · Base Functions
statistics variance base

The var() function calculates the variance of a numeric vector. Variance is a fundamental statistical measure that quantifies the spread of data around the mean.

Syntax

var(x, y = NULL, na.rm = FALSE, use)

Parameters

ParameterTypeDefaultDescription
xnumericREQUIREDA numeric vector or matrix
ynumericNULLOptional second vector for pairwise variance
na.rmlogicalFALSEIf TRUE, missing values are removed before computing
usecharacter”everything”How to handle missing values: “everything”, “all.obs”, “complete.obs”, “pairwise.complete.obs”

Examples

Basic usage

x <- c(2, 4, 4, 4, 5, 5, 7, 9)
var(x)
# [1] 4.571429

Handling missing values

x_with_na <- c(1, 2, NA, 4, 5)

# Without na.rm - returns NA
var(x_with_na)
# [1] NA

# With na.rm = TRUE
var(x_with_na, na.rm = TRUE)
# [1] 3.7

Variance of a matrix

# var() can compute variance-covariance matrix
m <- matrix(c(1, 2, 3, 4, 5, 6), nrow = 3, ncol = 2)
var(m)
#          [,1]       [,2]
# [1,] 2.333333  2.333333
# [2,] 2.333333  2.333333

Pairwise variance

# Variance between two vectors
var(c(1, 2, 3), c(4, 5, 6))
# [1] 0.5

Common Patterns

Standard deviation from variance

x <- c(2, 4, 4, 4, 5, 5, 7, 9)
sd_x <- sqrt(var(x))
sd_x
# [1] 2

Variance by group

Use tapply() to compute variance for groups:

df <- data.frame(
  group = c("A", "A", "A", "B", "B", "B"),
  value = c(1, 2, 3, 10, 11, 12)
)

tapply(df$value, df$group, var)
#        A        B 
# 1.000000 1.000000

See Also