r - R中因子之间的斯 PIL 曼等级相关性

标签 r correlation

我有如下数据:

directions <- c("North", "East", "South", "South")
x<-factor(directions, levels= c("North", "East", "South", "West"))

cities <- c("New York","Rome","Paris","London")
y<-factor(cities, levels= c("New York","Rome","Paris","London"))

如何计算 x 之间的 Spearman 等级相关性和 y ?

编辑

正如@user20650 和@dcarlson 评论所建议的那样,变量必须具有一个排名,使得一个值大于或小于另一个值。情况是这样,因为 North , East等是根据它们在文档中的存在排序的关键字。

最佳答案

要获得 Spearman 与因子的相关性,您必须将它们转换为它们的基础数字代码:

cor(as.numeric(x), as.numeric(y), method="spearman")
# [1] 0.9486833
cor.test(as.numeric(x), as.numeric(y), method="spearman")
# 
#   Spearman's rank correlation rho
# 
# data:  as.numeric(x) and as.numeric(y)
# S = 0.51317, p-value = 0.05132
# alternative hypothesis: true rho is not equal to 0
# sample estimates:
#       rho 
# 0.9486833 
# 
# Warning message:
# In cor.test.default(as.numeric(x), as.numeric(y), method = "spearman") :
#   Cannot compute exact p-value with ties

请注意关于关系的警告,这使得计算精确的 p 值变得困难。您可以使用 spearman_test包装内coin对于有关系的数据:
library(coin)
spearman_test(as.numeric(x)~as.numeric(y))
# 
#   Asymptotic Spearman Correlation Test
# 
# data:  as.numeric(x) by as.numeric(y)
# Z = 1.6432, p-value = 0.1003
# alternative hypothesis: true rho is not equal to 0

关于r - R中因子之间的斯 PIL 曼等级相关性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60021083/

相关文章:

r - 如何对 R 中共享类别的多个列进行 one-hot 编码?

r - 如何在R中的巨大数据集中计算两个变量的相关性?

python - 为什么 NUMPY correlate 和 corrcoef 返回不同的值以及如何在 "normalize"模式下关联 "full"?

python - 使用 matplotlib 在 Python 中绘制颜色不匹配的相关图

python - 与 Pandas 的加权相关系数

r - 向三角形中心弯曲线(ggplot2)

r - randomForest R 包的奇怪结果

r - 当列名是年份时减去列

r - 在 Windows 中使用 sendmailR

python - scipy.stats.pearsonr(x, y) 中的非相关检验是什么?