【问题标题】:How can I melt a matrix data frame in R with 2 variables and 1 value column?如何在 R 中融合具有 2 个变量和 1 个值列的矩阵数据框?
【发布时间】:2021-02-21 18:08:01
【问题描述】:

我的数据如下所示:

    col1 col2 col3 
col1 100  25  30  
col2 25  200  50
col3 30  50   300

其中列名和行名是 c("col1", "col2", "col3")

我希望它看起来像这样:

Var1 Var2 Value
col1 col1 100
col1 col2 25
col1 col3 30
col2 col1 25
col2 col2 200
col2 col3 50
col3 col1 30
col3 col2 50
col3 col3 300

我正在尝试 reshape2::melt 但它没有给我我正在寻找的结果melt(df),感谢任何帮助!

谢谢。

【问题讨论】:

    标签: r dataframe tidyr reshape2 melt


    【解决方案1】:

    在为table创建属性后,我们可以使用base Ras.data.frame

    as.data.frame.table(m1)
    #   Var1 Var2 Freq
    #1 col1 col1  100
    #2 col2 col1   25
    #3 col3 col1   30
    #4 col1 col2   25
    #5 col2 col2  200
    #6 col3 col2   50
    #7 col1 col3   30
    #8 col2 col3   50
    #9 col3 col3  300
    

    数据

    m1 <- structure(c(100L, 25L, 30L, 25L, 200L, 50L, 30L, 50L, 300L),
    .Dim = c(3L, 
    3L), .Dimnames = list(c("col1", "col2", "col3"), c("col1", "col2", 
    "col3")))
    

    【讨论】:

      【解决方案2】:

      tidyr 包就是你所需要的

      library(tidyr)
      
      df <- gather(df, 'Var2', 'Value' 2:4)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-08-07
        • 2023-03-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-12-25
        相关资源
        最近更新 更多