[英]Spearman rank correlation between factors in R
我有如下數據:
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
和y
之間的 Spearman 等級相關性?
編輯
正如@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 值變得困難。 您可以在包coin
使用spearman_test
來獲取具有關系的數據:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.