将两个字段转换为 R 中的一个唯一键
Transposing two fields to one unique key in R
我有一个包含 productID、Seller1Name、Seller1Price、Seller2Name、Seller2Price 的数据框,如下所示。
table (DF) 是唯一的 productID:
ProductID Seller1Name Seller1Price Seller2Name Seller2Price
1 A X
2 B Y
3 C Z
所需的输出应该是 DF:
ProductID Seller Price
1 A
1 X
2 B
2 Y
3 C
3 Z
我尝试使用重塑包,但结果很奇怪:
Output <-melt(DF, Id = c("ProductID"))
有更好的方法吗?
在 data.table v1.9.5
中,当前开发版本 melt
for data.tables 获得了一个新功能 -- 能够融合到多个列..
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
# 2: 1 X
# 3: 2 B
# 4: 2 Y
# 5: 3 C
# 6: 3 Z
HTH
另一个选项是 merged.stack
来自 splitstackshape
library(splitstackshape)
res <- merged.stack(DF, var.stubs=c('Name', 'Price'), sep='var.stubs',
atStart=FALSE)[,2:= NULL][]
setnames(res, 2, 'Seller')
res
# ProductID Seller Price
#1: 1 A
#2: 1 X
#3: 2 B
#4: 2 Y
#5: 3 C
#6: 3 Z
我有一个包含 productID、Seller1Name、Seller1Price、Seller2Name、Seller2Price 的数据框,如下所示。 table (DF) 是唯一的 productID:
ProductID Seller1Name Seller1Price Seller2Name Seller2Price
1 A X
2 B Y
3 C Z
所需的输出应该是 DF:
ProductID Seller Price
1 A
1 X
2 B
2 Y
3 C
3 Z
我尝试使用重塑包,但结果很奇怪:
Output <-melt(DF, Id = c("ProductID"))
有更好的方法吗?
在 data.table v1.9.5
中,当前开发版本 melt
for data.tables 获得了一个新功能 -- 能够融合到多个列..
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
# 2: 1 X
# 3: 2 B
# 4: 2 Y
# 5: 3 C
# 6: 3 Z
HTH
另一个选项是 merged.stack
来自 splitstackshape
library(splitstackshape)
res <- merged.stack(DF, var.stubs=c('Name', 'Price'), sep='var.stubs',
atStart=FALSE)[,2:= NULL][]
setnames(res, 2, 'Seller')
res
# ProductID Seller Price
#1: 1 A
#2: 1 X
#3: 2 B
#4: 2 Y
#5: 3 C
#6: 3 Z