这是我实际拥有的data.frame
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
我想像这样重组它
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
我真的不知道该怎么做,我是stackoverflow社区的新手,所以如果我的帖子有问题告诉我,我下次会知道的
答案 0 :(得分:2)
使用
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
答案 1 :(得分:1)
这里是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
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))