spearman correlation by group in R

前端 未结 4 723
心在旅途
心在旅途 2020-11-30 04:57

How do you calculate Spearman correlation by group in R. I found the following link talking about Pearson correlation by group. But when I tried to replace the type with s

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-30 05:42

    How about this for a base R solution:

    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(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:

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

提交回复
热议问题