【问题标题】:How to put correlation results into a table in R?如何将相关结果放入R中的表格中?
【发布时间】:2021-06-25 01:12:15
【问题描述】:

我在数据框中的列之间运行了一些相关性计算,如下所示:

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")

我正在试图弄清楚如何将这些结果放入他们自己的表格中,给出如下表格:

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")
}))

但这看起来不正确,我不确定如何将我的关联代码压缩到表格中 - 我可以使用哪些函数来处理我的关联代码?

输入数据示例:

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"
))

【问题讨论】:

    标签: r dataframe correlation


    【解决方案1】:

    您可以使用 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
    

    【讨论】:

      【解决方案2】:

      我们可以使用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
      

      【讨论】:

        猜你喜欢
        • 2021-04-03
        • 1970-01-01
        • 2021-07-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-27
        • 2022-06-24
        • 1970-01-01
        相关资源
        最近更新 更多