-1

I have a matrix which looks (structurally) something like this:

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

I need to turn it into:

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

I cannot for the life of me come up with a simple solution that doesn't involve loops, and yet I know it should be straightforward.

I have tried the following, but it doesn't work at all:

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

I feel like there's probably an even more straightforward solution that doesn't require a package, but I'm stuck.

ajrwhite
  • 7,728
  • 1
  • 11
  • 24
  • Using `reshape` - `reshape(data.frame(dat), idvar="id", direction="long", varying=-1, v.names="shop", timevar=NULL)` – thelatemail Feb 02 '16 at 00:56

1 Answers1

0

If the expected output is matrix, then cbind the first column of the initial matrix (after replicating) with the other columns and then order by first column (a base R option).

 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"      

If we want a data.frame as output, melt can be used after converting to data.frame

library(reshape2)
 melt(as.data.frame(m1), id.var='id')[-2]
akrun
  • 874,273
  • 37
  • 540
  • 662