如何将相关结果放入 R 中的 table?

How to put correlation results into a table in R?

我有一些相关性计算我在数据框中的列之间 运行 像这样:

cor(df$length, df$col1, method = c("pearson"), use = "complete.obs")
cor(df$length, df$col1, method = c("spearman"), use = "complete.obs")

cor(df$length, df$col2, method = c("pearson"), use = "complete.obs")
cor(df$length, df$col2, method = c("spearman"), use = "complete.obs")

cor(df$length, df$col3, method = c("pearson"), use = "complete.obs")
cor(df$length, df$col3, method = c("spearman"), use = "complete.obs")

我正在尝试弄清楚如何将这些结果转化为它们自己的 table,给出 table 如:

Col   Pearsons  Spearman
Col1   0.1       0.2
Col2   0.003     0.5
Col3   0.6       0.9

我一直在尝试修改类似问题的代码:

result <- do.call(rbind, by(df, df$length, FUN = function(x) {
  tmp <- cor.test(x$Col1, x$length, method = "spearman")
}))

但这看起来不对,我不确定如何将我的相关代码压缩到 table - 我可以使用什么函数来处理我的相关代码?

示例输入数据:

df <- structure(list(length = c(144001L, 1731L, 337L), col1 = c(3L, 
3L, 4L), col2 = c(8L, 2L, 6L), col3 = c(18L, 
1L, 1L)), row.names = c(NA, -3L), class = c("data.table", "data.frame"
))

您可以使用 apply 函数族来做到这一点。

t(sapply(df[, -1], function(x) {
  c(Pearsons = cor(df$length, x, method = "pearson", use = "complete.obs"), 
    Spearman = cor(df$length, x, method = "spearman", use = "complete.obs"))
}))

#       Pearsons   Spearman
#col1 -0.5072948 -0.8660254
#col2  0.7503742  0.5000000
#col3  0.9999643  0.8660254

我们可以使用tidyverse

library(dplyr)
library(tidyr)
df %>%
  summarise(across(starts_with('col'), ~ 
    list(tibble(Pearsons = cor(length, ., method = 'pearson',
            use = 'complete.obs'),
      Spearman = cor(length,., method = "spearman", use = 'complete.obs'))))) %>% 
 pivot_longer(cols = everything()) %>% 
 unnest(c(value))

-输出

# A tibble: 3 x 3
  name  Pearsons Spearman
  <chr>    <dbl>    <dbl>
1 col1    -0.507   -0.866
2 col2     0.750    0.5  
3 col3     1.00     0.866