0

I would like to reformat a generated dataframe so that I can add more information afterwards.

So lets say I have this df:

testdf <- data.frame(replicate(5,sample(1:50,5,rep=TRUE)))
testdf

  X1 X2 X3 X4 X5
1 38 20 47 43 39
2 25 27 25 45  9
3  9  1 44 12  8
4 48 19 21 46 13
5 26 50 26 35 38

With an additional column at the beginning:

new_column = c(100, 101, 102, 103, 104)
finaldf <- cbind(new_column, testdf)
colnames(finaldf) <- c("ID", "Article1", "Article2", "Article3", "Article4", "Article5")
finaldf

   ID Article1 Article2 Article3 Article4 Article5
1 100       34       22       23       22       19
2 101       43       19       43       14       11
3 102       32       40        5       12        9
4 103       37        5       37       15        2
5 104       41       19       30       42       49

Now I would like to transform this df in something like this:

   ID Article
  100       34
  100       22
  100       23       
  100       22
  100       19
  101       43
  101       19
  101       43
  101       14
  101       11
  102       32
  102       40
  102        5
  102       12
  102        9
  103       37
  103        5
  103       37
  103       15
  103        2
  104       41
  104       19
  104       30
  104       42
  104       49

Does anyone know how I can solve this elegantly?

Timothy_Goodman
  • 393
  • 1
  • 5
  • 18

1 Answers1

1

You can reshape from wide to long like this:

longdf <- reshape(finaldf, varying = c(2:6), direction = "long", idvar = "ID", sep = "", timevar = "Article")

> head(longdf)
       ID Article
100.1 100      16
101.1 101      43
102.1 102      28
103.1 103      44
104.1 104      26
100.2 100      44
Sven
  • 1,203
  • 1
  • 5
  • 14