【问题标题】:Transposing two fields to one unique key in R [duplicate]将两个字段转置为R中的一个唯一键[重复]
【发布时间】:2015-03-31 23:09:01
【问题描述】:

我有一个包含 productID、Seller1Name、Seller1Price、Seller2Name、Seller2Price 的数据框,如下所示。 表 (DF) 按 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 包,但结果很奇怪:

Output <-melt(DF, Id = c("ProductID"))

有没有更好的方法来做到这一点?

【问题讨论】:

  • 这是一个简单的reshape 操作 - reshape(dat, idvar="ProductID", direction="long", varying=list(c(2,4),c(3,5)), v.names=c("Seller","Price") )
  • ...如果您不想依赖 data.frame 中变量的位置,请使用 varying=lapply(c("Name","Price"),grep,x=names(dat)) 或类似名称。

标签: r dataframe reshape


【解决方案1】:

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    $1
# 2:         1      X    $3
# 3:         2      B    $3
# 4:         2      Y    $6
# 5:         3      C    $2
# 6:         3      Z    $1

HTH

【讨论】:

  • 这达到了我的目的!
【解决方案2】:

另一个选项是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    $1
 #2:         1    X    $3
 #3:         2    B    $3
 #4:         2    Y    $6
 #5:         3    C    $2
 #6:         3    Z    $1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    • 2016-04-16
    • 2013-11-10
    • 2021-08-28
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多