1

I'm still a new user in R and I know there are tons of questions of converting wide format to long format. However, I fail to get the results that I want. I tried to use reshape, tidyr,, however, I still don't get the results that I want.

My data looks like below (it is just a part of it N)

     i1 i2 i3 i4 i5 i6 i7 i8 i9 i10 i11 i12 i13 i14 i15 i16 i17 i18 i19 i20 i21 i22 i23 i24 i25 i26 i27
207    0  1  0  0  1  0  0  1  0   0   0   1   0   0   1   0   1   0   0   1   1   1   0   0   0   0   1
334    0  0  0  0  0  0  0  0  0   0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0   0   1
344    0  1  1  0  0  1  0  0  0   1   0   0   1   0   1   0   1   1   0   1   0   1   1   1   0   0   1
432    1  0  1  1  0  0  0  0  0   1   0   1   0   1   1   0   1   1   0   1   1   0   0   0   0   1   1
616    0  1  1  1  1  0  0  0  0   0   0   1   0   1   1   0   0   1   1   0   0   0   0   0   0   1   1
667    1  0  0  0  0  0  0  0  0   0   0   0   0   1   0   0   0   0   0   0   0   0   0   0   0   0   0

My ideal dataset

0 207 i1  => the observation of the 207th student at the first item. 
 1 207 i2
 0 207 i3

. . Could somebody help me how to code? Thank you in advance.

sm925
  • 2,648
  • 1
  • 16
  • 28
Newuser
  • 45
  • 3
  • 1
    What have you tried that hasn't worked? This seems like it should be covered by the wide-to-long classics like https://stackoverflow.com/q/2185252/5325862 – camille Jan 28 '20 at 18:58

2 Answers2

1

One option is to create a row names column and then use pivot_longer to create a 3-column data.frame with rowname, column name and the values as the three columns

library(dplyr)
library(tidyr)
as.data.frame(m1) %>%
    rownames_to_column('rn') %>%
    pivot_longer(cols = -rn)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Using melt from data.table:

library(data.table)
setDT(df, keep.rownames = T); melt(df, id.vars = "rn")
sm925
  • 2,648
  • 1
  • 16
  • 28