1

here it is the data.frame I actually have

Mp  Id1 Arbre_1 Id2 Arbre2
1   69  500     66  555
2   68  435     66  243
3   72  246     70  184
4   59  112     64  128
5   63  200     64  199
6   54  378     55  178

I'd like to reorganize it like this

Mp  ID  Arbre
1   69  500
1   66  555
2   68  435
2   66  243
3   72  246
3   70  184
4   59  112
4   64  128
5   63  200
5   64  199
6   54  378
6   55  178

I really have no idea how to do that, I'm new in the stackoverflow community so if something's wrong with my post tell me, I will know for the next time

camille
  • 16,432
  • 18
  • 38
  • 60
Alexis Begni
  • 106
  • 9
  • 1
    Does this answer your question? [Reshaping multiple sets of measurement columns (wide format) into single columns (long format)](https://stackoverflow.com/questions/12466493/reshaping-multiple-sets-of-measurement-columns-wide-format-into-single-columns) – camille Nov 20 '19 at 18:35
  • @akrun no, that wouldn't serve the R SO community well. This is a question that's been asked many times; the post I flagged for has the [tag:r-faq] tag because it's so common. But if you see duplicate posts, flagging them certainly helps improve the community – camille Nov 20 '19 at 18:38

2 Answers2

1

Here is an option with melt

library(data.table)
melt(setDT(df1), measure  = patterns("^Id\\d+", "^Arbre_?\\d+"),
       value.name = c("Id", "Arbre"))[, variable := NULL][]
#    Mp Id Arbre
# 1:  1 69   500
# 2:  2 68   435
# 3:  3 72   246
# 4:  4 59   112
# 5:  5 63   200
# 6:  6 54   378
# 7:  1 66   555
# 8:  2 66   243
# 9:  3 70   184
#10:  4 64   128
#11:  5 64   199
#12:  6 55   178

data

df1 <- structure(list(Mp = 1:6, Id1 = c(69L, 68L, 72L, 59L, 63L, 54L
), Arbre_1 = c(500L, 435L, 246L, 112L, 200L, 378L), Id2 = c(66L, 
66L, 70L, 64L, 64L, 55L), Arbre2 = c(555L, 243L, 184L, 128L, 
199L, 178L)), class = "data.frame", row.names = c(NA, -6L))
akrun
  • 874,273
  • 37
  • 540
  • 662
1

using

names(df )<- sub("_","",names(df))

reshape(df,2:ncol(df),idvar = "Mp",sep="",dir="long")

    Mp time Id Arbre
1.1  1    1 69   500
2.1  2    1 68   435
3.1  3    1 72   246
4.1  4    1 59   112
5.1  5    1 63   200
6.1  6    1 54   378
1.2  1    2 66   555
2.2  2    2 66   243
3.2  3    2 70   184
4.2  4    2 64   128
5.2  5    2 64   199
6.2  6    2 55   178
Onyambu
  • 67,392
  • 3
  • 24
  • 53