r - reshaping a data frame duplicating IDs -
this question has answer here:
this 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 result want this:
id 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 approach solution, had no luck.
we can use melt
data.table
can take multiple measure
patterns
convert 'wide' 'long' format.
library(data.table) melt(setdt(df), measure = patterns("^a", "^b"), value.name = c("a", "b"))[, variable := null][order(id)] # id 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
Comments
Post a Comment