Executing the above code outputs:
"Sample variance: 10" "Standard deviation: 3.16227766016838" "Standard deviation squared: 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)
# Calculate 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))
Executing the above code outputs:
"Covariance of height and weight: 62.5"
"Covariance matrix:"
height weight
height 62.5 62.5
weight 62.5 92.5
YouTip
R Examples