R cor() Function - Computing Correlation Coefficients
The R cor() function is used to compute the correlation coefficient between two or more variables.
The correlation coefficient measures the degree of linear correlation between variables, ranging from -1 to 1. A value of 1 means perfect positive correlation, -1 means perfect negative correlation, and 0 means no correlation.
The syntax of the cor() function is as follows:
cor(x, y = NULL, method = c("pearson", "kendall", "spearman"))
Parameter Description:
-
x Input numeric vector or matrix.
-
y Optional, a second vector or matrix.
-
method Correlation coefficient type: pearson (default, linear correlation), kendall, spearman (rank correlation).
Example
Create two sets of data
height
<-
c
(
160
,
165
,
170
,
175
,
180
)
Height (cm)
weight
<-
c
(
55
,
60
,
65
,
70
,
80
)
Weight (kg)
Compute the correlation coefficient
r
<-
cor
(
height, weight
)
(
paste
(
"Correlation Coefficient Between Height and Weight:"
,
round
(
r,
3
)
)
)
Compute the correlation matrix of multiple variables
sleep_hours
<-
c
(
7
,
6.5
,
8
,
7.5
,
6
)
df
<-
data.frame
(
height, weight, sleep_hours
)
(
"Correlation coefficient matrix:"
)
(
round
(
cor
(
df
)
,
3
)
)
The output of the code above is:
[1] "身高与体重的相关系数: 0.993"
[1] "相关系数矩阵:"
height weight sleep_hours
height 1.000 0.993 -0.784
weight 0.993 1.000 -0.729
sleep_hours -0.784 -0.729 1.000
R Language Examples