R cov() Function - Calculate Covariance
The R cov() function is used to calculate the covariance between two variables.
Covariance measures how two variables change together. A positive covariance indicates changes in the same direction, while a negative covariance indicates changes in opposite directions. It is the basis for calculating the correlation coefficient.
The syntax of the cov() function is as follows:
cov(x, y = NULL, method = c("pearson", "kendall", "spearman"))
Parameter Description:
xInput a numeric vector or matrix.
yOptional, the second vector or matrix.
Example
# Advertising investment (10,000 yuan) and sales (10,000 yuan)
ad_spend <- c(10, 15, 12, 18, 20, 14, 22, 16)
sales <- c(50, 65, 55, 72, 80, 60, 88, 68)
# Calculate covariance
cov_value <- cov(ad_spend, sales)
print(paste("Covariance of advertising investment and sales:", cov_value))
# Calculate correlation coefficient
cor_value <- cor(ad_spend, sales)
print(paste("Correlation coefficient:", round(cor_value, 3)))
# Verification: cor = cov / (sd(x) * sd(y))
manual_cor <- cov_value / (sd(ad_spend) * sd(sales))
print(paste("Manually calculated correlation coefficient:", round(manual_cor, 3)))
ad_spend <- c(10, 15, 12, 18, 20, 14, 22, 16)
sales <- c(50, 65, 55, 72, 80, 60, 88, 68)
# Calculate covariance
cov_value <- cov(ad_spend, sales)
print(paste("Covariance of advertising investment and sales:", cov_value))
# Calculate correlation coefficient
cor_value <- cor(ad_spend, sales)
print(paste("Correlation coefficient:", round(cor_value, 3)))
# Verification: cor = cov / (sd(x) * sd(y))
manual_cor <- cov_value / (sd(ad_spend) * sd(sales))
print(paste("Manually calculated correlation coefficient:", round(manual_cor, 3)))
Executing the above code produces the following output:
[1] "广告投入与销售额的协方差: 48.3571428571429" [1] "相关系数: 0.988" [1] "手动计算相关系数: 0.988"Other Extensions
R Language Example