在R中分组和分割数据帧

时间:2015-07-27 09:01:28

标签: r

以下是促销销售表,其中列出了促销活动所在的产品和组。

   Product.code  cgrp promo.from   promo.to
1    1100001369    12 2014-01-01 2014-03-01
2    1100001369 16 37 2014-01-01 2014-03-01
3    1100001448    12 2014-03-01 2014-03-01
4    1100001446    12 2014-03-01 2014-03-01
5    1100001629 11 30 2014-03-01 2014-03-01
6    1100001369 16 37 2014-03-01 2014-06-01
7    1100001368    12 2014-06-01 2014-07-01
8    1100001369    12 2014-06-01 2014-07-01
9    1100001368 11 30 2014-06-01 2014-07-01
10   1100001738 11 30 2014-06-01 2014-07-01
11   1100001629 11 30 2014-06-01 2014-06-01
12   1100001738 11 30 2014-07-01 2014-07-01
13   1100001619 11 30 2014-08-01 2014-08-01
14   1100001619 11 30 2014-08-01 2014-08-01
15   1100001629 11 30 2014-08-01 2014-08-01
16   1100001738    12 2014-09-01 2014-09-01
17   1100001738 16 37 2014-08-01 2014-08-01
18   1100001448    12 2014-09-01 2014-09-01
19   1100001446    12 2014-10-01 2014-10-01
20   1100001369    12 2014-11-01 2014-11-01
21   1100001547 16 37 2014-11-01 2014-11-01
22   1100001368 11 30 2014-11-01 2014-11-01

我正在尝试对product.code和cgrp进行分组,以便我可以了解特定组中产品的所有促销并进行进一步分析。

我尝试循环遍历整个data.frame。没有效率和错误。

完成此任务的有效方法是什么。

[编辑] 获取多个data.frame,如下所示

X =

   Product.code  cgrp promo.from   promo.to
3    1100001448    12 2014-03-01 2014-03-01
18   1100001448    12 2014-09-01 2014-09-01

Y =

   Product.code  cgrp promo.from   promo.to
1    1100001369    12 2014-01-01 2014-03-01
8    1100001369    12 2014-06-01 2014-07-01
20   1100001369    12 2014-11-01 2014-11-01

1 个答案:

答案 0 :(得分:1)

你可以split' cgrp'列并将数据集重新整形为“长”字样。格式为cSplit。然后,split数据集(' df1')由' Product.code'和' cgrp创建list(' lst')。

 library(splitstackshape)
 df1 <- as.data.frame(cSplit(df, 'cgrp', ' ', 'long'))
 lst <- split(df1, list(df1$Product.code, df1$cgrp), drop=TRUE)
 names(lst) <- paste0('dfN', seq_along(lst))

将数据集保存在list中可能会更好。但是,如果你想在全局环境中作为单独的对象,一个选项是list2env(不推荐)。

 list2env(lst, envir=.GlobalEnv)