我有一个数据框,其中包含如下所示的productID、Seller1Name、Seller1Price、Seller2Name、Seller2Price。 表 (DF) 根据产品 ID 是唯一的:
ProductID Seller1Name Seller1Price Seller2Name Seller2Price
1 A $1 X $3
2 B $3 Y $6
3 C $2 Z $1
所需的输出应该是 DF:
ProductID Seller Price
1 A $1
1 X $3
2 B $3
2 Y $6
3 C $2
3 Z $1
我尝试使用 reshape 包,但结果很奇怪:
Output <-melt(DF, Id = c("ProductID"))
有更好的方法吗?
最佳答案
在 data.table v1.9.5
,当前的开发版本,data.tables 的 melt
获得了一个新功能——能够熔化到多个列。
require(data.table) ## v1.9.5+
ans = melt(setDT(DF), measure=patterns("Name$", "Price$"),
value.name=c("seller", "price"))
我们只是提供要分组在一起的列,同时在 measure.vars
参数中熔化为列表。
现在,您可以删除 variable
列并重新排序,如下所示:
setorder(ans[, variable := NULL], ProductID)[]
# ProductID seller price
# 1: 1 A $1
# 2: 1 X $3
# 3: 2 B $3
# 4: 2 Y $6
# 5: 3 C $2
# 6: 3 Z $1
HTH
关于r - 将两个字段转换为 R 中的一个唯一键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29380114/