假设我有销售各种产品的三个销售代表的销售数据。困难在于每个销售代表销售的产品组合不同,而且数量也不一定相同:
Bob 销售产品 A、B 和 C
Mike 销售产品 A、B、C 和 D
Sara 销售产品 A、B 和 E
RepName Product SalesDollarAmt SalesQty
1 Bob A 43 3
2 Mike A 14 5
3 Sara A 53 1
4 Bob B 100 35
5 Mike B 215 80
6 Sara B 310 105
7 Bob C 5 8
8 Mike C 10 3
9 Mike D 105 50
10 Sara E 25 18
我想在产品上旋转它,这样结果看起来像这样:
RepName Product.1 SalesDollarAmt.1 SalesQty.1 Product.2 SalesDollarAmt.2 SalesQty.2 Product.3 SalesDollarAmt.3 SalesQty.3 Product.4 SalesDollarAmt.4 SalesQty.4
1 Bob A 43 3 B 100 35 C 5 8 <NA> 0 0
2 Mike A 14 5 B 215 80 C 10 3 D 105 50
3 Sara A 53 1 B 310 105 E 25 18 <NA> 0 0
如果他们都有相同的产品,我会按产品将它们过滤到单独的数据框中,然后在 RepName 上将它们重新组合在一起。我已经尝试了所有我能想到的spread
和dcast
。谢谢你的帮助!
示例数据帧的代码:
library(tidyverse)
# initial sales data
df <- tribble(
~RepName, ~Product, ~SalesDollarAmt, ~SalesQty,
#-------------------------------
"Bob", "A", 43, 3,
"Mike", "A", 14, 5,
"Sara", "A", 53, 1,
"Bob", "B", 100, 35,
"Mike", "B", 215, 80,
"Sara", "B", 310, 105,
"Bob", "C", 5, 8,
"Mike", "C", 10, 3,
"Mike", "D", 105, 50,
"Sara", "E", 25, 18
)
# ideally rotated data
df2 <- tribble(
~RepName, ~Product.1, ~SalesDollarAmt.1, ~SalesQty.1, ~Product.2, ~SalesDollarAmt.2, ~SalesQty.2, ~Product.3, ~SalesDollarAmt.3, ~SalesQty.3, ~Product.4, ~SalesDollarAmt.4, ~SalesQty.4,
#--------------------------------------------------------------
"Bob", "A", 43, 3, "B", 100, 35, "C", 5, 8, NA, 0, 0,
"Mike", "A", 14, 5, "B", 215, 80, "C", 10, 3, "D", 105, 50,
"Sara", "A", 53, 1, "B", 310, 105, "E", 25, 18, NA, 0, 0
)