是否有一个Python等效于R的Hmisc包中的spearman2函数?
R的Hmisc文件包(第149页)中说明: Spearman 2计算Spearman的rho秩相关的平方,并对其进行推广,其中x可以非单调地与y相关。这是通过计算(秩(x)、秩(x)^2)和y之间的斯皮尔曼倍数ρ平方来实现的是否有一个Python等效于R的Hmisc包中的spearman2函数?,python,r,Python,R,R的Hmisc文件包(第149页)中说明: Spearman 2计算Spearman的rho秩相关的平方,并对其进行推广,其中x可以非单调地与y相关。这是通过计算(秩(x)、秩(x)^2)和y之间的斯皮尔曼倍数ρ平方来实现的 我想知道Python中是否有一个等价的函数?或者,如果有人可以向我解释如何使用Hnisc包()源代码中的scipy.stats.spearmanr编写一个小函数来完成上面用斜体强调的计算,下面是该函数的源代码: spearman2.default <- functio
我想知道Python中是否有一个等价的函数?或者,如果有人可以向我解释如何使用Hnisc包()源代码中的scipy.stats.spearmanr编写一个小函数来完成上面用斜体强调的计算,下面是该函数的源代码:
spearman2.default <- function(x, y, p=1, minlev=0,
na.rm=TRUE, exclude.imputed=na.rm, ...)
{
if(p > 2)
stop('p must be 1 or 2')
y <- as.numeric(y)
if(is.character(x))
x <- factor(x)
if(na.rm) {
s <- !(is.na(x) | is.na(y))
if(exclude.imputed) {
im <- is.imputed(x) | is.imputed(y)
s <- s & !im
}
x <- x[s]; y <- y[s]
}
n <- length(x)
## If number of non-NA values is less then 3 then return a NA
## value.
if(n < 3)
return(c(rho2=NA,F=NA,df1=0,df2=n,P=NA,n=n,'Adjusted rho2'=NA))
## Find the number of unique values in x
u <- length(unique(x))
## If is a factor and unique values are greater then 2 then find the
## lm.fit.qr.bare without an intercept.
if(is.factor(x) && u > 2) {
if(minlev > 0) {
x <- combine.levels(x, minlev)
if(length(levels(x))<2) {
warning(paste('x did not have >= 2 categories with >=',
minlev,'of the observations'))
return(c(rho2=NA,F=NA,df1=0,df2=n,P=NA,n=n,'Adjusted rho2'=NA))
}
}
x <- model.matrix(~x, data=data.frame(x))
p <- ncol(x)-1
rsquare <- lm.fit.qr.bare(x, rank(y), intercept=FALSE)$rsquared
} else {
x <- as.numeric(x)
if(u < 3)
p <- 1
x <- rank(x)
rsquare <-
if(p==1)
cor(x, rank(y))^2
else {
x <- cbind(x, x^2)
lm.fit.qr.bare(x, rank(y), intercept=TRUE)$rsquared
}
}
df2 <- n-p-1
fstat <- rsquare/p/((1-rsquare)/df2)
pvalue <- 1-pf(fstat,p,df2)
rsqa <- 1 - (1 - rsquare)*(n-1)/df2
x <- c(rsquare,fstat,p,df2,pvalue,n,rsqa)
names(x) <- c("rho2","F","df1","df2","P","n","Adjusted rho2")
x
}
spearman2.default 2)
停止('p必须为1或2')
Y