【问题标题】:Transforming Matrix in R在 R 中变换矩阵
【发布时间】:2021-05-11 12:56:23
【问题描述】:

我目前在将矩阵转换为以下格式时遇到问题。如何以最简单的方式在 R 中实现这一点?理想情况下,我想将第二个矩阵用作数据框。非常感谢!

      Estonia Germany Poland
Estonia 0       2       3
Germany 2       0       4
 Poland  3      4       0


Country1      Country2     Weight
Estonia       Estonia        0
Estonia       Germany        2
Estonia       Poland         3
Germany       Estonia        2
...

【问题讨论】:

    标签: r dataframe matrix tidyverse data-transform


    【解决方案1】:

    如果矩阵被称为mat,你可以使用:

    library(tibble)
    library(tidyr)
    
    mat %>%
      as.data.frame() %>%
      rownames_to_column('Country1') %>%
      pivot_longer(cols = -Country1, names_to = 'Country2', values_to = 'Weight')
    
    #  Country1 Country2 Weight
    #  <chr>    <chr>     <int>
    #1 Estonia  Estonia       0
    #2 Estonia  Germany       2
    #3 Estonia  Poland        3
    #4 Germany  Estonia       2
    #5 Germany  Germany       0
    #6 Germany  Poland        4
    #7 Poland   Estonia       3
    #8 Poland   Germany       4
    #9 Poland   Poland        0
    

    数据

    mat <- structure(c(0L, 2L, 3L, 2L, 0L, 4L, 3L, 4L, 0L), .Dim = c(3L, 
    3L), .Dimnames = list(c("Estonia", "Germany", "Poland"), c("Estonia", 
    "Germany", "Poland")))
    

    【讨论】:

      【解决方案2】:

      另一种非tidyverse方式:

      df <- as.data.frame(as.table(mat))
      names(df) <- c("Country1", "Country2", "Weight")
      df
      #   Country1 Country2 Weight
      # 1  Estonia  Estonia      0
      # 2  Germany  Estonia      2
      # 3   Poland  Estonia      3
      # 4  Estonia  Germany      2
      # 5  Germany  Germany      0
      # 6   Poland  Germany      4
      # 7  Estonia   Poland      3
      # 8  Germany   Poland      4
      # 9   Poland   Poland      0
      

      【讨论】:

        【解决方案3】:

        我们可以使用melt

        library(reshape2)
        melt(mat)
        

        数据

        mat <- structure(c(0L, 2L, 3L, 2L, 0L, 4L, 3L, 4L, 0L), .Dim = c(3L, 
        3L), .Dimnames = list(c("Estonia", "Germany", "Poland"), c("Estonia", 
        "Germany", "Poland")))
        

        【讨论】:

          【解决方案4】:

          另一个基本 R 选项

          > cbind(expand.grid(dimnames(mat)), Weight = c(mat))
               Var1    Var2 Weight
          1 Estonia Estonia      0
          2 Germany Estonia      2
          3  Poland Estonia      3
          4 Estonia Germany      2
          5 Germany Germany      0
          6  Poland Germany      4
          7 Estonia  Poland      3
          8 Germany  Poland      4
          9  Poland  Poland      0
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-03-16
            • 1970-01-01
            • 2013-02-12
            相关资源
            最近更新 更多