在 R 中将宽型矩阵转换为长型矩阵(可能使用 reshape2 和 melt)

Turning a wide-form matrix into long-form in R (possibly with reshape2 and melt)

我有一个矩阵(在结构上)看起来像这样:

     id            1st         2nd          3rd        4th         5th
[1,] "aaaaa1"      "Tesco"     "Sainsbury"  "M&S"      "Waitrose"  "Asda"
[2,] "bbbbb2"      "Sainsbury" "Tesco"      "Waitrose" "Asda"      "M&S"

我需要把它变成:

     id            shop
[1,] "aaaaa1"      "Tesco"
[2,] "aaaaa1"      "Sainsbury"
[3,] "aaaaa1"      "M&S"
[4,] "aaaaa1"      "Waitrose"
[5,] "aaaaa1"      "Asda"
[6,] "bbbbb2"      "Sainsbury"
[7,] "bbbbb2"      "Tesco" (ETC.)

我一辈子都想不出一个不涉及循环的简单解决方案,但我知道它应该很简单。

我尝试了以下方法,但根本不起作用:

library(reshape2)
meltedPredictionsMatrix = melt(widePredictionsMatrix, id.vars="id")

我觉得可能有一个不需要包的更直接的解决方案,但我被卡住了。

如果预期输出为 matrix,则 cbind 初始矩阵的第一列(复制后)与其他列,然后 order 第一列(a base R选项)。

 res <- cbind(id= m1[,1][row(m1[,-1])], shop=c(m1[,-1]))
 res[order(res[,1]),]
 #      id       shop       
 #[1,] "aaaaa1" "Tesco"    
 #[2,] "aaaaa1" "Sainsbury"
 #[3,] "aaaaa1" "M&S"      
 #[4,] "aaaaa1" "Waitrose" 
 #[5,] "aaaaa1" "Asda"     
 #[6,] "bbbbb2" "Sainsbury"
 #[7,] "bbbbb2" "Tesco"    
 #[8,] "bbbbb2" "Waitrose" 
 #[9,] "bbbbb2" "Asda"     
 #[10,] "bbbbb2" "M&S"      

如果我们想要一个data.frame作为输出,melt可以在转换为data.frame后使用

library(reshape2)
 melt(as.data.frame(m1), id.var='id')[-2]