簡體   English   中英

是否有 R function 用於計算 df 中每一行的 Spearman 相關系數並將其寫為向量?

[英]Is there an R function for calculating Spearman correlation coefficient for each row in df and writing it as a vector?

我想知道是否有一個 R function 或 package 用於計算 df 中每一行的 Spearman 相關系數並將其寫為向量?

首先是可重現的示例:

deviation <- c(5.712840e-03, 5.712840e-02, 5.712840e-01, 5.712940e-01,5.712840e-06)
number <- c(45, 60, 16, 70, 19)
df  <- data.frame(deviation, number)

我的 df 有 5 行 2 列。 我想計算每一行的 Spearman 相關性,以便稍后我可以在我的 df 中再添加一個具有 5 個 rho 的列。 我知道有一個計算相關系數的 function cor.test。 但是,它並不能幫助我解決我的任務,因為在它之后我只會得到一個系數

test <- cor.test(deviation, number, method="spearman")
test

它只會給出一個 rho。

請任何人向我推薦一些可以幫助解決此任務的 R 中的 package 或 function。

除了 Ben Bolker 的評論,我猜你正在尋找這樣的東西:

cor.test(df$deviation, df$number, method = "spearman")  

    Spearman's rank correlation rho

data:  df$deviation and df$number
S = 12, p-value = 0.5167
alternative hypothesis: true rho is not equal to 0
sample estimates:
rho 
0.4 

為了將估計值放入數據框中,您可以使用broom package 中的tidy()

library(broom)
cor.test(df$deviation, df$number, method = "spearman") %>% tidy()

給出:

# A tibble: 1 x 5
  estimate statistic p.value method                          alternative
     <dbl>     <dbl>   <dbl> <chr>                           <chr>      
1      0.4        12   0.517 Spearman's rank correlation rho two.sided  

然后您可以制作 function 並使用它:

cor_fun <- function(df) cor.test(df$deviation, df$number, method = "spearman") %>% tidy()
cor_fun(df)

暫無
暫無

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

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