Open In App

How to Create a Covariance Matrix in R?

Last Updated : 04 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will discuss how to create a Covariance Matrix in the R Programming Language.

Covariance is the statistical measure that depicts the relationship between a pair of random variables that shows how the change in one variable causes changes in another variable. It is a measure of the degree to which two variables are linearly associated. 

A covariance matrix is a square matrix that shows the covariance between different variables of a data frame. This helps us in understanding the relationship between different variables in a dataset.

To create a Covariance matrix from a data frame in the R Language, we use the cov() function. The cov() function forms the variance-covariance matrix. It takes the data frame as an argument and returns the covariance matrix as result.

Syntax: 

cov( df )

Parameter:

  • df: determines the data frame for creating covariance matrix.

A positive value for the covariance matrix indicates that two variables tend to increase or decrease sequentially. A negative value for the covariance matrix indicates that as one variable increases, the second variable tends to decrease.

Example 1: Create Covariance matrix

R




# create sample data frame
sample_data <- data.frame( var1 = c(86, 82, 79, 83, 66),
                           var2 = c(85, 83, 80, 84, 65),
                           var3 = c(107, 127, 137, 117, 170))
  
# create covariance matrix
cov( sample_data )


Output:

       var1   var2   var3
var1   60.7   63.9 -185.9
var2   63.9   68.3 -192.8
var3 -185.9 -192.8  585.8

Example 2: Create Covariance matrix

R




# create sample data frame
sample_data <- data.frame( var1 = rnorm(20,5,23),
                           var2 = rnorm(20,8,10))
  
# create covariance matrix
cov( sample_data )


Output:

          var1      var2
var1 642.00590 -14.66349
var2 -14.66349  88.71560

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads