在 R 中转换数据框

Transforming a data frame in R

我在 R 中有一个数据框,其中包含客户信息和每种产品的销售额。产品是具有多个值的字段。销售是一个单独的领域。我想转换 table 以便每个产品的销售额都有自己的列,以便每个客户一行(而不是每个产品每个客户一行)。我看过有关如何转置 table 的信息,但这是不同的。下面是我开始的两个简化示例和所需的最终结果。真实情况会有更多的栏目、客户和产品。

起点:

start <- data.frame(client = c(1,1,1,2,2,2), 
product=c("Product1","Product2","Product3","Product1","Product2","Product3"),
          sales = c(100,500,300,200,400,600))

输出:

  client  product sales
1      1 Product1   100
2      1 Product2   500
3      1 Product3   300
4      2 Product1   200
5      2 Product2   400
6      2 Product3   600

以下是所需的最终结果:

end <- data.frame(client = c(1,2),
                      Product1 = c(100,200), Product2 = c(500,400),
                      Product3 = c(300,600))

输出:

  client Product1 Product2 Product3
1      1      100      500      300
2      2      200      400      600

如何在 R 中从头到尾转换这些数据?在此先感谢您的帮助!

> install.packages("reshape2") # to install 'reshape2'.
> library(reshape2)
> dcast(start, client ~ product)
Using sales as value column: use value.var to override.
  client Product1 Product2 Product3
1      1      100      500      300
2      2      200      400      600