我有如下数据:
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/