To create a covariance matrix for a data frame in R, you can use the cov()
function. A covariance matrix is a table that shows the covariance between pairs of variables in a data set.
In this article, we will explore how to create a covariance matrix for an R data frame using the cov()
function.
Method: Use cov() Function
The cov()
function in R is used to calculate the covariance matrix for a data frame. Here’s the syntax:
cov(df)
The following example shows how to create a covariance matrix in R using the cov()
function.
Create Covariance Matrix for R Data Frame Using cov() Function
Let’s see how we can use the cov()
function to create a covariance matrix in R:
# Create data frame
df <- data.frame(Value = c(108, 120, 135, 95, 98, 105),
Reading = c(110, 97, 91, 89, 80, 85))
# Create covariance matrix
matrix <- cov(df)
# Print covariance matrix
print(matrix)
Output: 👇️
Value Reading
Value 186.5667 172.5667
Reading 172.5667 178.5667
In this example, the cov()
function calculates the covariance matrix for the Value
and Reading
columns of the data frame.