Ariel Ariel - 23 days ago 5
R Question

reshaping a data frame duplicating IDs

This is my dataframe:

df <- data.frame(ID = c(1,2,3), A1 = c("a1","a3","a5"),
B1 = c("b1","b3","b5"), A2 = c("a2","a4","a6"), B2 = c("b2","b4","b6"))


And the result I want is this:

ID A B
1 1 a1 b1
2 1 a2 b2
3 2 a3 b3
4 2 a4 b4
5 3 a5 b5
6 3 a6 b6


I tried to approach to a solution, but I had no luck.

Answer

We can use melt from data.table which can take multiple measure patterns to convert from 'wide' to 'long' format.

library(data.table)
melt(setDT(df), measure = patterns("^A", "^B"), 
          value.name = c("A", "B"))[, variable := NULL][order(ID)]
#  ID  A  B
#1:  1 a1 b1
#2:  1 a2 b2
#3:  2 a3 b3
#4:  2 a4 b4
#5:  3 a5 b5
#6:  3 a6 b6