R Tutorial R Charts & Graphs R Statistics R References

R - Variance



The R var() function returns variance of all elements present in the argument. The syntax for using this function is given below:

Syntax

var(x, na.rm = FALSE)

Parameters

x Required. Specify numeric vector.
na.rm Optional. Specify TRUE to remove NA or NaN values before the computation. Default is FALSE.

Return Value

Returns variance of all elements present in the argument.

Example:

The example below shows the usage of var() function.

vec <- c(10, 55, 25, -56, 30, 99)
cat("Variance of all elements of vec:", var(vec), "\n")

mat <- matrix(c(10, 55, 25, -56, 30, 99), ncol=2)
cat("\nThe matrix contains:\n")
print(mat)
cat("\nVariance of elements along first column:", var(mat[,1]))
cat("\nVariance of elements along second column:", var(mat[,2]))
cat("\nVariance of elements along first row:", var(mat[1,]))
cat("\nVariance of elements along second row:", var(mat[2,]))

The output of the above code will be:

Variance of all elements of vec: 2631.767 

The matrix contains:
     [,1] [,2]
[1,]   10  -56
[2,]   55   30
[3,]   25   99

Variance of elements along first column: 525
Variance of elements along second column: 6030.333
Variance of elements along first row: 2178
Variance of elements along second row: 312.5

Using na.rm parameter

The na.rm parameter can be set TRUE to remove NA or NaN values before the computation.

Example:

Consider the example below to see the usage of na.rm parameter.

v1 <- c(10, 55, 25, -56, 30, 99, NA)
v2 <- c(10, 55, 25, -56, 30, 99, NaN)

cat("Variance of all elements of v1:", var(v1), "\n")
cat("Variance after removing NA:", var(v1, na.rm=TRUE), "\n")

cat("\nVariance of all elements of v2:", var(v2), "\n")
cat("Variance after removing NaN:", var(v2, na.rm=TRUE), "\n")

The output of the above code will be:

Variance of all elements of v1: NA 
Variance after removing NA: 2631.767 

Variance of all elements of v2: NA 
Variance after removing NaN: 2631.767 

❮ R Statistical Functions