簡體   English   中英

是否有 Python 等效於來自 Hmisc package 的 spearman2 function 的 Python?

[英]Is there a Python equivalent to the spearman2 function from the Hmisc package for R?

R 的 Hmisc package 的文檔(第 149 頁)說:

spearman2 計算 Spearman 的 rho 秩相關的平方及其泛化,其中 x 可以與 y 非單調相關。 這是通過計算 (rank(x), rank(x)^2) 和 y 之間的 Spearman 多重 rho 平方來完成的。

我想知道Python中是否有等效的function? 或者,如果有人可以向我解釋如何使用 scipy.stats.spearmanr 編寫一個小的 function 可以進行上面斜體強調的計算?

來自Hnisc package的源代碼( https://github.com/harrelfe/Hmisc/blob/master/R/biVar.s ),這里是ZC1C4145268E17A94D的源代碼:

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
}

function lm.fit.qr.bare在此文件( https://github.com/harrelfe/Hmisc/blob/master/R/Misc.s )第 213 行中定義。

看起來您還需要chol2inv function,請在此處查看詳細信息: https://www.rdocumentation.org/packages/base/versions/3.6.1/topics/chol2inv

這需要一些工作,但您絕對可以在 python 中翻譯它。 祝你好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM