将两个字段转换为R中的一个唯一键 [英] Transposing two fields to one unique key in R
问题描述
我有一个数据框,其中有一个productID,Seller1Name,Seller1Price,Seller2Name,Seller2Price如下。
表(DF)由productID唯一:
I have a dataframe that has a productID, Seller1Name, Seller1Price, Seller2Name, Seller2Price as below. The table (DF) is unique by productID:
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包,但结果很简单:
I tried using the reshape package but the results are funky:
Output <-melt(DF, Id = c("ProductID"))
有更好的方法吗?
推荐答案
在 data.table v1.9.5
,当前版本,融化
对于data.tables已经获得了一个新功能 - 可以融合到多个列。
In data.table v1.9.5
, current devel version, melt
for data.tables has gained a new feature -- able to melt on to multiple columns..
require(data.table) ## v1.9.5+
ans = melt(setDT(DF), measure=patterns("Name$", "Price$"),
value.name=c("seller", "price"))
我们只提供要组合在一起的列,作为 measure.vars
参数。
We just provide the columns to be grouped together while melting as a list in measure.vars
argument.
现在,您可以删除变量
列并重新排列如下:
Now, you can remove variable
column and reorder as follows:
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中的一个唯一键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!