Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R var() Function - Calculating Variance

R var() Function - Calculating Variance

R Language Examples R Language Examples

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:

Example

Create a dataset

data

<-

c

(

2

,

4

,

6

,

8

,

10

)

Calculate the sample variance

result.

var

<-

var

(

data

)

print

(

paste

(

"Sample variance:"

, result.

var

)

)

Verification: variance = standard deviation^2

print

(

paste

(

"Standard deviation:"

,

sd

(

data

)

)

)

print

(

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

)

print

(

paste

(

"Covariance of height and weight:"

, cov_xy

)

)

Covariance matrix

m

<-

cbind

(

height, weight

)

print

(

"Covariance matrix:"

)

print

(

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 R Language Examples