当前位置: 动力学知识库 > 问答 > 编程问答 >

r - 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.

网友答案:

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
分享给朋友:
您可能感兴趣的文章:
随机阅读: