melt to two variable columns

前端 未结 1 997
孤独总比滥情好
孤独总比滥情好 2020-12-23 15:01

I have the following variables in a data frame:

[1] \"Type\"   \"I.alt\"  \"idx06\"  \"idx07\"  \"idx08\" \"farve1\" \"farve2\"

If I do:

相关标签:
1条回答
  • 2020-12-23 15:29

    This doesn't answer your question about cast, but you could certainly subset and do two melts, followed by a merge:

    dm1 <- melt(d[,c("Type","I.alt","idx06","idx07","idx08")], id=c("Type","I.alt"))
    dm2 <- melt(d[,c("Type","I.alt","farve1","farve2")], id=c("Type","I.alt"))
    colnames(dm2) <- c("Type", "I.alt", "variable2", "value2")
    dm <- merge(dm1, dm2)
    

    Or, equivalently, do one melt (like you're currently doing) then subset the melted dataframe twice (idx <- variable %in% c("idx06","idx07","idx08") as one and !idx as the other) and merge that output.

    Either way you get what you want:

    > head(dm)
                  Type I.alt variable    value variable2 value2
    1 Alvorligere vold  1154    idx08 1.108696    farve1    red
    2 Alvorligere vold  1154    idx08 1.108696    farve2    red
    3 Alvorligere vold  1154    idx07 1.027174    farve1    red
    4 Alvorligere vold  1154    idx07 1.027174    farve2    red
    5 Alvorligere vold  1154    idx06 1.000000    farve1    red
    6 Alvorligere vold  1154    idx06 1.000000    farve2    red
    
    0 讨论(0)
提交回复
热议问题