【发布时间】:2014-02-25 16:24:32
【问题描述】:
我是 R 新手,我一直在尝试旋转从 CSV 文件中读取的数据框。原始 CSV 包含 5,000 个项目编号,在我的示例中我使用了前五个。我使用数据透视的最终结果应该显示每个项目编号的次数与完成的付款和付款类型一样多。例如,原始表格如下所示:
ITEM NUMBER P1 P2 P3 P4 PType1 PType2 PType3 PType4
697884 270 255 170 0 CASH CA VI
697885 100 1160 310 580 CASH AX VI CA
697886 1515 1455 1765 970 CASH AX VI CA
697887 0 0 0 0
697888 1755 3610 1950 0 AX VI CA
通过使用 pivot 我想得到一个这样的表:
ITEM NUMBER Payment PaymentType
697884 270 CASH
697884 255 CA
697884 170 VI
...(下一项)
我当前的数据框包含 9 个变量,其中项目编号为 NUM,付款金额为 int,付款类型为 Factor。 谢谢!
structure(list(ITEM.NUMBER = 697884:697888, Payment1 = c(270L,
100L, 1515L, 0L, 1755L), Payment2 = c(255L, 1160L, 1455L, 0L,
3610L), Payment3 = c(170L, 310L, 1765L, 0L, 1950L), Payment4 = c(0L,
580L, 970L, 0L, 0L), PaymentType1 = structure(c(3L, 3L, 3L, 1L,
2L), .Label = c("", "AX", "CASH"), class = "factor"), PaymentType2 = structure(c(3L,
2L, 2L, 1L, 4L), .Label = c("", "AX", "CA", "VI"), class = "factor"),
PaymentType3 = structure(c(3L, 3L, 3L, 1L, 2L), .Label = c("",
"CA", "VI"), class = "factor"), PaymentType4 = structure(c(1L,
2L, 2L, 1L, 1L), .Label = c("", "CA"), class = "factor")), .Names = c("ITEM.NUMBER",
"Payment1", "Payment2", "Payment3", "Payment4", "PaymentType1",
"PaymentType2", "PaymentType3", "PaymentType4"), row.names = c(NA,
-5L), class = "data.frame")
【问题讨论】:
-
plyr包中的melt对此非常有效。 -
Brandon,您能否详细说明一下您建议如何使用带有我拥有的变量的公式以及如何在付款金额和付款类型之间建立联系
-
melt(dat, id = c('ITEM', 'NUMBER'), variable.name = 'PaymentType', value.name = 'Payment') -
谢谢@Ramnath,你给我的公式将所有内容生成一个列表而不是一个表格。它为票号和付款金额创建一个列表,并在另一个票号和付款类型列表的下方。是因为融化功能吗?如果是这样,我如何将此列表放入表格中?
-
删除列名中的空格后使用
melt(dat, id = 'ITEMNUMBER')。我检查了一下,它确实给了我一个数据框。