You can use the cor() function in R to calculate correlation coefficients between variables.
Here are the most common ways to use this function:
Method 1: Calculate Pearson Correlation Coefficient Between Two Variables
cor(df$x, df$y)
Use the Pearson correlation coefficient when calculating the correlation between two continuous variables. (e.g. height and weight)
Method 2: Calculate Pearson Correlation Coefficient Between All Numeric Variables in Data Frame
cor(df)
This method will return a
correlation matrix that contains the Pearson correlation coefficient between each pairwise combination of numeric variables in a data frame.
Method 3: Calculate Spearman Correlation Coefficient Between Two Variables
cor(df$x, df$y, method='spearman')
Use the Spearman correlation coefficient when calculating the correlation between two ranked variables. (e.g. rank of a student’s math exam score vs. rank of their science exam score in a class)
Method 4: Calculate Kendall’s Correlation Coefficient Between Two Variables
cor(df$x, df$y, method='kendall')
如果您希望使用斯皮尔曼相关,但样本量较小且存在许多并列等级,请使用 Kendall 相关系数。
以下示例显示了如何在实践中使用每种方法,其中包含 R 中的以下数据框,该数据框显示八个不同学生的学习小时数、参加的模拟考试次数和期末考试成绩:
#create data framedf <- data.frame(hours=c(1, 1, 3, 2, 4, 3, 5, 6), prac_exams=c(4, 3, 3, 2, 3, 2, 1, 4), score=c(69, 74, 74, 70, 89, 85, 99, 90))#view data framedf hours prac_exams score1 1 4 692 1 3 743 3 3 744 2 2 705 4 3 896 3 2 857 5 1 998 6 4 90
示例 1:计算两个变量之间的皮尔逊相关系数
以下代码演示如何使用 cor() 函数计算小时和分数变量之间的 Pearson 相关系数:
#calculate Pearson correlation coefficient between hours and scorecor(df$hours, df$score)[1] 0.8600528
小时和分数之间的皮尔逊相关系数原来是 0.86。
请注意,如果数据框中有 NA 值,则可以使用参数 use='complete.obs' 仅使用没有 NA 值的行:
#calculate Pearson correlation coefficient and ignore any rows with NAcor(df$hours, df$score, use='complete.obs')
示例 2:计算所有数值变量之间的皮尔逊相关系数
以下代码演示如何使用 cor() 函数创建包含数据框中所有数值变量之间的 Pearson 相关系数的相关矩阵:
#calculate Pearson correlation coefficient between all numeric variablescor(df) hours prac_exams scorehours 1.0000000 -0.1336063 0.8600528prac_exams -0.1336063 1.0000000 -0.3951028score 0.8600528 -0.3951028 1.0000000
以下是解释输出的方法:
小时和prac_exams之间的皮尔逊相关系数为 -.13。
小时数和分数之间的皮尔逊相关系数为 .86。
prac_exams和分数之间的皮尔逊相关系数为 -.39。
注意:每个变量与自身之间的皮尔逊相关系数始终为 1,这就是为什么沿相关矩阵对角线的每个值为 1 的原因。
示例 3:计算两个变量之间的斯皮尔曼相关系数
以下代码演示如何使用 cor() 函数计算小时和prac_exams变量之间的 Spearman 相关系数:
#calculate Spearman correlation coefficient between hours and prac_examscor(df$hours, df$prac_exams, method='spearman')[1] -0.1250391
小时和prac_exams之间的斯皮尔曼相关系数原来是 -.125。
示例 4:计算两个变量之间的肯德尔相关系数
以下代码演示如何使用 cor() 函数计算小时和prac_exams变量之间的 Kendall 相关系数:
#calculate Kendall's correlation coefficient between hours and prac_examscor(df$hours, df$prac_exams, method='kendall')[1] -0.1226791
肯德尔小时和prac_exams之间的相关系数原来是 -.123。
其他资源
以下教程介绍如何在 R 中执行其他常见任务:
如何在 R 中计算滚动相关性 如何在 R 中计算
自相关 如何在 R中计算偏相关