这是reshape()
解决方案。
关键一点是varying=
参数可以采用与长格式的单个变量相对应的宽格式的列名称向量列表。在这种情况下,列"x1", "x2", "x3"
原始数据帧中的一列被发送到长数据帧中的一列,列"y1, y2, y3"
将进入第二列,依此类推。
# Read in the original data, x, from Andrie's answer
res <- reshape(x, direction = "long", idvar = "id",
varying = list(c("x1","x2", "x3"),
c("y1", "y2", "y3"),
c("z1", "z2", "z3")),
v.names = c("xvalue", "yvalue", "zvalue"),
timevar = "xsource", times = c("x1", "x2", "x3"))
# id v xsource xvalue yvalue zvalue
# 1.x1 1 2.5 x1 2 10 200
# 2.x1 2 4.2 x1 3 25 300
# 1.x2 1 2.5 x2 4 20 150
# 2.x2 2 4.2 x2 7 35 350
# 1.x3 1 2.5 x3 5 15 170
# 2.x3 2 4.2 x3 6 40 400
最后,需要几个纯粹的装饰步骤才能获得看起来的结果exactly如你的问题所示:
res <- res[order(res$id, res$xsource), c(1,3,4,5,6,2)]
row.names(res) <- NULL
res
# id xsource xvalue yvalue zvalue v
# 1 1 x1 2 10 200 2.5
# 2 1 x2 4 20 150 2.5
# 3 1 x3 5 15 170 2.5
# 4 2 x1 3 25 300 4.2
# 5 2 x2 7 35 350 4.2
# 6 2 x3 6 40 400 4.2