简体   繁体   English

R中按组划分的spearman相关性

[英]spearman correlation by group in R

How do you calculate Spearman correlation by group in R. I found the following link talking about Pearson correlation by group.你如何在 R 中按组计算 Spearman 相关性。我发现以下链接按组讨论 Pearson 相关性。 But when I tried to replace the type with spearman, it does not work.但是当我尝试用 spearman 替换类型时,它不起作用。

https://stats.stackexchange.com/questions/4040/r-compute-correlation-by-group https://stats.stackexchange.com/questions/4040/r-compute-correlation-by-group

How about this for a base R solution:对于基本的 R 解决方案,这个怎么样:

df <- data.frame(group = rep(c("G1", "G2"), each = 10),
                 var1 = rnorm(20),
                 var2 = rnorm(20))

r <- by(df, df$group, FUN = function(X) cor(X$var1, X$var2, method = "spearman"))
# df$group: G1
# [1] 0.4060606
# ------------------------------------------------------------ 
# df$group: G2
# [1] 0.1272727

And then, if you want the results in the form of a data.frame:然后,如果您想要 data.frame 形式的结果:

data.frame(group = dimnames(r)[[1]], corr = as.vector(r))
#   group      corr
# 1    G1 0.4060606
# 2    G2 0.1272727

EDIT : If you prefer a plyr -based solution, here is one:编辑:如果您更喜欢基于plyr的解决方案,这里是一个:

library(plyr)
ddply(df, .(group), summarise, "corr" = cor(var1, var2, method = "spearman"))

very old question, but this tidy & broom solution is extremely straightforward.很老的问题,但这个tidybroom解决方案非常简单。 Thus I have to share the approach:因此,我必须分享方法:

set.seed(123)
df <- data.frame(group = rep(c("G1", "G2"), each = 10),
                 var1 = rnorm(20),
                 var2 = rnorm(20))

library(tidyverse)
library(broom)

df  %>% 
  group_by(group) %>%
  summarize(correlation = cor(var1, var2,, method = "sp"))
# A tibble: 2 x 2
  group correlation
  <fct>       <dbl>
1 G1        -0.200 
2 G2         0.0545

# with pvalues and further stats
df %>% 
  nest(-group) %>% 
  mutate(cor=map(data,~cor.test(.x$var1, .x$var2, method = "sp"))) %>%
  mutate(tidied = map(cor, tidy)) %>% 
  unnest(tidied, .drop = T)
# A tibble: 2 x 6
  group estimate statistic p.value method                          alternative
  <fct>    <dbl>     <dbl>   <dbl> <chr>                           <chr>      
1 G1     -0.200        198   0.584 Spearman's rank correlation rho two.sided  
2 G2      0.0545       156   0.892 Spearman's rank correlation rho two.sided 

Since some time/ dplyr version, you need to write this to get results like above and no errors:由于某些时间/ dplyr版本,您需要编写此代码以获得上述结果并且没有错误:

df %>% 
  nest(data = -group) %>%
  mutate(cor=map(data,~cor.test(.x$var1, .x$var2, method = "sp"))) %>%
  mutate(tidied = map(cor, tidy)) %>% 
  unnest(tidied) %>% 
  select(-data, -cor)

Here's another way to do it:这是另一种方法:

# split the data by group then apply spearman correlation
# to each element of that list
j <- lapply(split(df, df$group), function(x){cor(x[,2], x[,3], method = "spearman")})

# Bring it together
data.frame(group = names(j), corr = unlist(j), row.names = NULL)

Comparing my method, Josh's method, and the plyr solution using rbenchmark:比较我的方法、Josh 的方法和使用 rbenchmark 的 plyr 解决方案:

Dason <- function(){
    # split the data by group then apply spearman correlation
    # to each element of that list
    j <- lapply(split(df, df$group), function(x){cor(x[,2], x[,3], method = "spearman")})

    # Bring it together
    data.frame(group = names(j), corr = unlist(j), row.names = NULL)
}

Josh <- function(){
    r <- by(df, df$group, FUN = function(X) cor(X$var1, X$var2, method = "spearman"))
    data.frame(group = attributes(r)$dimnames[[1]], corr = as.vector(r))
}

plyr <- function(){
    ddply(df, .(group), summarise, "corr" = cor(var1, var2, method = "spearman"))
}


library(rbenchmark)
benchmark(Dason(), Josh(), plyr())

Which gives the output这给出了输出

> benchmark(Dason(), Josh(), plyr())
     test replications elapsed relative user.self sys.self user.child sys.child
1 Dason()          100    0.19 1.000000      0.19        0         NA        NA
2  Josh()          100    0.24 1.263158      0.22        0         NA        NA
3  plyr()          100    0.51 2.684211      0.52        0         NA        NA

So it appears my method is slightly faster but not by much.所以看起来我的方法稍微快一点但不是很多。 I think Josh's method is a little more intuitive.我认为 Josh 的方法更直观一些。 The plyr solution is the easiest to code up but it's not the fastest (but it sure is a lot more convenient)! plyr 解决方案是最容易编码的,但它不是最快的(但它确实更方便)!

If you want an efficient solution for large numbers of groups then data.table is the way to go.如果您想为大量组提供有效的解决方案,那么data.table是您要走的路。

library(data.table)
DT <- as.data.table(df)
setkey(DT, group)
DT[,list(corr = cor(var1,var2,method = 'spearman')), by = group]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM