Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R cor() Function - Computing Correlation Coefficients

R cor() Function - Computing Correlation Coefficients

R Language Examples R Language Examples

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:

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

)

print

(

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

)

print

(

"Correlation coefficient matrix:"

)

print

(

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 R Language Examples