【问题标题】:How to apply a function for Spearman's rank correlation coefficient in R?如何在 R 中应用 Spearman 等级相关系数的函数?
【发布时间】:2017-05-11 13:53:21
【问题描述】:

我想编写一个代码来应用计算数据集中列组合之间的 Spearman 等级相关性的功能。我有以下数据集:

library(openxlsx)
data <-read.xlsx("e:/LINGUISTICS/mydata.xlsx", 1);

A    B    C    D
go   see  get  eat
see  get  eat  go
get  go   go   get
eat  eat  see  see

函数 cor(rank(x), rank(y), method = "spearman") 仅测量两列之间的相关性,例如A 和 B 之间:

cor(rank(data$A), rank(data$B), method = "spearman")

但我需要计算所有可能的列组合(AB、AC、AD、BC、BD、CD)之间的相关性。我为此编写了以下函数:

wert <- function(x, y) { cor(rank(x), rank(y), method = "spearman") }

我不知道如何在我的函数中实现所有可能的列组合(AB、AC、AD、BC、BD、CD)以便自动获得所有结果,因为我的真实数据有更多的列,而且作为具有相关分数的矩阵,例如如下表:

    A     B     C     D
A   1     0.3   0.4   0.8
B   0.3   1     0.6   0.5
C   0.4   0.6   1     0.1
D   0.8   0.5   0.1   1

有人可以帮帮我吗?

【问题讨论】:

    标签: r function correlation rank


    【解决方案1】:

    我认为您可以只创建一个函数(pairedcolumns),然后将您的函数(spearman)应用于您提供给它的数据框中的每一对列。

    #This function works on a data frame (x) usingwhichever other function (fun) you select by making all pairs of columns possible.
    pairedcolumns <- function(x,fun) 
    {
      n <- ncol(x)##find out how many columns are in the data frame
    
      foo <- matrix(0,n,n)
      for ( i in 1:n)
      {
        for (j in 1:n)
        {
          foo[i,j] <- fun(x[,i],x[,j])
    }
    }
     colnames(foo)<-rownames(foo)<-colnames(x)
    return(foo)
    }
    
     results<-pairedcolumns(yourdataframe[,2:8], function)
    

    【讨论】:

      【解决方案2】:

      您不需要rankcor 已经计算了与 method = "spearman" 的 Spearman 等级相关性。如果您想要 data.frame 的所有列之间的相关性,只需将 data.frame 传递给cor,即cor(data, method = "spearman")。你应该学习help("cor")

      如果您想手动执行此操作,请使用combn 函数。

      PS:你的额外挑战是你实际上有因子变量。无序因子的等级是一个奇怪的概念,但 R 在这里只使用排序规则。由于cor 正确地期望数字输入,你应该先做data[] &lt;- lapply(data, as.integer)

      【讨论】:

      • 感谢您的回答。但如果没有rank(),它就不起作用,因为 Spearman 等级相关性比较了两个变量的等级。为了获得因子变量的排名列表,我应该使用rank()
      • @Volod cor 在内部计算 method = "spearman" 的排名。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-18
      • 1970-01-01
      • 2011-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多