在 dplyr 中使用 funs 的相关性

Nic*_*ick 2 r dplyr

我想使用 dplyr 找到 data.frame 中各个列的等级相关性。

我确信这个问题有一个简单的解决方案,但我认为问题在于我在使用 cor 函数时无法在 dplyr 中的 summarise_each_ 中使用两个输入。

对于以下 df:

df <- data.frame(Universe=c(rep("A",5),rep("B",5)),AA.x=rnorm(10),BB.x=rnorm(10),CC.x=rnorm(10),AA.y=rnorm(10),BB.y=rnorm(10),CC.y=rnorm(10))
Run Code Online (Sandbox Code Playgroud)

我想获得所有 .x 和 .y 组合之间的等级相关性。我在下面的函数中遇到了问题????

cor <- df %>% group_by(Universe) %>% 
summarize_each_(funs(cor(.,method = 'spearman',use = "pairwise.complete.obs")),????)
Run Code Online (Sandbox Code Playgroud)

我希望cor只包含相关对: AA.x.AA.y , AA.x,BB.y, ... 对于每个宇宙。

请帮忙!

Wal*_*ltS 5

另一种方法是只调用cor一次函数,因为这将计算所有所需的相关性。重复调用cor可能是大型数据集的性能问题。执行此操作并提取带有标签的相关对的代码可能如下所示:

#
# calculate correlations and display in matrix format
#
cor_matrix <- df %>% group_by(Universe) %>%
              do(as.data.frame(cor(.[,-1], method="spearman", use="pairwise.complete.obs")))
#
# to add row names
#
cor_matrix1 <- cor_matrix %>%  
              data.frame(row=rep(colnames(.)[-1], n_groups(.))) 
#
# calculate correlations and display in column format
#
num_col=ncol(df[,-1])
out_indx <-  which(upper.tri(diag(num_col))) 
cor_cols <- df %>% group_by(Universe) %>%
            do(melt(cor(.[,-1], method="spearman", use="pairwise.complete.obs"), value.name="cor")[out_indx,])
Run Code Online (Sandbox Code Playgroud)