R cov() Function - Computing Covariance
The R cov() function is used to compute the covariance between two variables.
Covariance measures how two variables change together. Positive covariance indicates change in the same direction, negative covariance indicates change in opposite directions. It is the basis for computing the correlation coefficient.
The syntax of the cov() function is as follows:
cov(x, y = NULL, method = c("pearson", "kendall", "spearman"))
Parameter Description:
-
x Input numeric vector or matrix.
-
y Optional, a second vector or matrix.
Example
Advertising spending (in ten thousand yuan) and sales (in ten thousand yuan)
ad_spend
<-
c
(
10
,
15
,
12
,
18
,
20
,
14
,
22
,
16
)
sales
<-
c
(
50
,
65
,
55
,
72
,
80
,
60
,
88
,
68
)
Compute the covariance
cov_value
<-
cov
(
ad_spend, sales
)
(
paste
(
"Covariance of Advertising Spending and Sales:"
, cov_value
)
)
Compute the correlation coefficient
cor_value
<-
cor
(
ad_spend, sales
)
(
paste
(
"Correlation Coefficient:"
,
round
(
cor_value,
3
)
)
)
Verification: cor = cov / (sd(x) * sd(y))
manual_cor
<-
cov_value
/
(
sd
(
ad_spend
)
sd
(
sales
)
)
(
paste
(
"Manually Computed Correlation Coefficient:"
,
round
(
manual_cor,
3
)
)
)
The output of the code above is:
[1] "广告投入与销售额的协方差: 48.3571428571429"
[1] "相关系数: 0.988"
[1] "手动计算相关系数: 0.988"
R Language Examples