R var() Function - Calculating Variance
The R var() function is used to calculate the variance of a sample.
Variance is the square of the standard deviation, measuring how far data deviates from the mean. The larger the variance, the more dispersed the data.
The syntax of the var() function is as follows:
var(x, y = NULL, na.rm = FALSE)
Parameter Description:
-
x Input numeric vector.
-
y Optional, a second vector. When provided, the covariance of x and y is calculated.
-
na.rm A boolean value, default FALSE, sets whether to remove missing values NA.
Example
Create a dataset
data
<-
c
(
2
,
4
,
6
,
8
,
10
)
Calculate the sample variance
result.
var
<-
var
(
data
)
(
paste
(
"Sample variance:"
, result.
var
)
)
Verification: variance = standard deviation^2
(
paste
(
"Standard deviation:"
,
sd
(
data
)
)
)
(
paste
(
"Squared standard deviation:"
,
sd
(
data
)
^
2
)
)
The output of the code above is:
[1] "样本方差: 10"
[1] "标准差: 3.16227766016838"
[1] "标准差平方: 10"
var() can also calculate the covariance of two variables:
Example
Two variables: height (cm) and weight (kg)
height
<-
c
(
160
,
165
,
170
,
175
,
180
)
weight
<-
c
(
55
,
60
,
65
,
70
,
80
)
Compute the covariance
cov_xy
<-
var
(
height, weight
)
(
paste
(
"Covariance of height and weight:"
, cov_xy
)
)
Covariance matrix
m
<-
cbind
(
height, weight
)
(
"Covariance matrix:"
)
(
var
(
m
)
)
The output of the code above is:
[1] "身高和体重的协方差: 62.5"
[1] "协方差矩阵:"
height weight
height 62.5 62.5
weight 62.5 92.5
R Language Examples