在非參數統計中,不看數據的實際數值,單純比較兩組變量的值的排名是通用的基本方法,但在客觀數據中,很多變量的關系都是非線性的,其他的方法不是對樣本數據的大小和線性有要求,就是只能對比數據的差異性,而不能展示這種非線性的單調性,比如想知道練習時間與游戲段位的關系,雖然從結果上看是正相關,但在過程中的體現可能是進步速度非常快后趨于穩定,其他的函數方法會漏掉這種細節。
以下是一個例子:
set.seed(123)
# 生成數據:學習時間增加,成績總體上升但非線性
Hours <- sort(runif(50, 1, 10)) # 1到10小時,均勻分布
Score <- 50 + 10 * sqrt(Hours) + rnorm(50, 0, 5) # 非線性關系+噪聲# 構建數據框
df <- data.frame(Hours, Score)
head(df)# 方法1:直接使用cor.test()
result <- cor.test(df$Hours, df$Score, method = "spearman")
print(result)# 方法2:手動計算(驗證原理)
rank_Hours <- rank(df$Hours)
rank_Score <- rank(df$Score)
n <- nrow(df)
rho_manual <- 1 - (6 * sum((rank_Hours - rank_Score)^2)) / (n * (n^2 - 1))
cat("手動計算的Spearman rho:", rho_manual, "\n")library(ggplot2)
ggplot(df, aes(x = Hours, y = Score)) +geom_point() +geom_smooth(method = "lm", se = FALSE, color = "red") + # 線性趨勢線(對比用)labs(title = "學習時間與成績的Spearman相關 (rho=0.72)")
輸出:
Spearman's rank correlation rhodata: df$Hours and df$Score
S = 5248, p-value < 2.2e-16
alternative hypothesis: true rho is not equal to 0
sample estimates:rho
0.7479952 手動計算的Spearman rho: 0.7479952
從結果可以看到,結果顯示0.748,屬于正相關。而圖像顯示,如果用一般的方法,直接用線性函數去擬合,會忽略實際數據中彎曲的分布,即不知道數據在實際中的增長方向,會對后續數據的加工使用造成錯覺。