r - 将两个字段转换为 R 中的一个唯一键

标签 r dataframe reshape

我有一个数据框,其中包含如下所示的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/

相关文章:

python - DataFrame基于多列应用函数,也为多列设置值

scala - spark DataFrame "as"方法的使用

r - 使用each() 和reshape2::dcast 聚合数据

r - R中使用read.csv、read_csv或read_excel读取数据时如何指定数值的位数

R data.table lapply 带剪切功能

r - 如何迭代到网站的最后一页并在 .csv 文件中逐行写入数据?

python - Pandas 0.21 在 get_dummies() 之后重新索引()

从宽变量组 reshape 到长变量组

reshape 数据框以在列中创建唯一值列表

r - 获取 S4 对象的插槽值?