She*_*don 4 r ordinal correlation
我想测试两个序数变量的斯皮尔曼相关性。
x=c(1,2,3)
y=c(4,3,6)
x=ordered(x)
y=ordered(y)
cor(x,y,methods="spearman")
Run Code Online (Sandbox Code Playgroud)
我总是收到“cor(x, y) 中的错误:‘x’必须是数字”
这样做的正确方法是什么?
两种方法:
使用as.numeric。
x=c(1,2,3)
y=c(4,3,6)
x=ordered(x)
y=ordered(y)
cor(as.numeric(x), as.numeric(y), method="spearman")
[1] 0.5
Run Code Online (Sandbox Code Playgroud)请注意,这并不是将x 和 y 简单地视为连续数。它将他们视为等级。
as.numeric(y)
[1] 2 1 3
Run Code Online (Sandbox Code Playgroud)
此方法将允许您忽略 NA 值。
x=c(1,2,3, NA)
y=c(4,3,6, 7)
x=ordered(x)
y=ordered(y)
cor(as.numeric(x), as.numeric(y),
method="spearman", use="pairwise.complete.obs")
[1] 0.5
Run Code Online (Sandbox Code Playgroud)
pspearman您可以使用将处理订购因素的包。
x=c(1,2,3)
y=c(4,3,6)
x=ordered(x)
y=ordered(y)
library(pspearman)
spearman.test(x,y)
Spearman's rank correlation rho
data: x and y
S = 2, p-value = 1
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho
0.5
Run Code Online (Sandbox Code Playgroud)或者如果你想减少一些输出,你可以使用:
spearman.test(x,y)$estimate
rho
0.5
Run Code Online (Sandbox Code Playgroud)