如何使用重塑程序包重塑此数据帧 [英] How to reshape this dataframe with the reshape package
本文介绍了如何使用重塑程序包重塑此数据帧的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个非常大的数据帧,结构如下:
id x1 x2 x3 y1 y2 y3 z1 z2 z3 v
1 2 4 5 10 20 15 200 150 170 2.5
2 3 7 6 25 35 40 300 350 400 4.2
我需要创建如下数据帧:
id xsource xvalue yvalue zvalue v
1 x1 2 10 200 2.5
1 x2 4 20 150 2.5
1 x3 5 15 170 2.5
2 x1 3 25 300 4.2
2 x2 7 35 350 4.2
2 x3 6 40 400 4.2
我非常确定我必须使用重塑程序包来完成此操作,但我无法得到我想要的。
你能帮帮我吗?
谢谢
推荐答案
以下是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
最后,需要几个纯粹的装饰步骤才能使结果看起来完全,如您的问题所示:
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
这篇关于如何使用重塑程序包重塑此数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文