13

我在 R 中有一个非常大的数据框,并且想将其他列中每个不同值的两列相加,例如,假设我们在一天内有各种商店的交易数据框的数据,如下所示

shop <- data.frame('shop_id' = c(1, 1, 1, 2, 3, 3), 
  'shop_name' = c('Shop A', 'Shop A', 'Shop A', 'Shop B', 'Shop C', 'Shop C'), 
  'city' = c('London', 'London', 'London', 'Cardiff', 'Dublin', 'Dublin'), 
  'sale' = c(12, 5, 9, 15, 10, 18), 
  'profit' = c(3, 1, 3, 6, 5, 9))

这是:

shop_id  shop_name    city      sale profit
   1     Shop A       London    12   3
   1     Shop A       London    5    1
   1     Shop A       London    9    3
   2     Shop B       Cardiff   15   6
   3     Shop C       Dublin    10   5
   3     Shop C       Dublin    18   9

我想总结每家商店的销售额和利润:

shop_id  shop_name    city      sale profit
   1     Shop A       London    26   7
   2     Shop B       Cardiff   15   6
   3     Shop C       Dublin    28   14

我目前正在使用以下代码来执行此操作:

 shop_day <-ddply(shop, "shop_id", transform, sale=sum(sale), profit=sum(profit))
 shop_day <- subset(shop_day, !duplicated(shop_id))

它工作得很好,但正如我所说,我的数据框很大(140,000 行,37 列和近 100,000 个唯一行,我想求和)并且我的代码需要很长时间才能运行,然后最终说它已经耗尽内存。

有谁知道最有效的方法来做到这一点。

提前致谢!

4

4 回答 4

18

**强制性数据表答案**

> library(data.table)
data.table 1.8.0  For help type: help("data.table")
> shop.dt <- data.table(shop)
> shop.dt[,list(sale=sum(sale), profit=sum(profit)), by='shop_id']
     shop_id sale profit
[1,]       1   26      7
[2,]       2   15      6
[3,]       3   28     14
> 

在事情变得更大之前,这听起来很好。

shop <- data.frame(shop_id = letters[1:10], profit=rnorm(1e7), sale=rnorm(1e7))
shop.dt <- data.table(shop)

> system.time(ddply(shop, .(shop_id), summarise, sale=sum(sale), profit=sum(profit)))
   user  system elapsed 
  4.156   1.324   5.514 
> system.time(shop.dt[,list(sale=sum(sale), profit=sum(profit)), by='shop_id'])
   user  system elapsed 
  0.728   0.108   0.840 
> 

如果您使用键创建 data.table,您将获得额外的速度提升:

shop.dt <- data.table(shop, key='shop_id')

> system.time(shop.dt[,list(sale=sum(sale), profit=sum(profit)), by='shop_id'])
   user  system elapsed 
  0.252   0.084   0.336 
> 
于 2012-08-02T17:13:44.787 回答
5

我认为最简洁的方法是dplyr

library(dplyr)
shop %>% 
  group_by(shop_id, shop_name, city) %>% 
  summarise_all(sum)
于 2018-12-10T17:50:56.887 回答
4

以下是如何使用基本 R 来加速这样的操作:

idx <- split(1:nrow(shop), shop$shop_id)
a2 <- data.frame(shop_id=sapply(idx, function(i) shop$shop_id[i[1]]),
                 sale=sapply(idx, function(i) sum(shop$sale[i])), 
                 profit=sapply(idx, function(i) sum(shop$profit[i])) )

时间减少到 0.75 秒,而我系统上的 ddply 汇总版本为 5.70 秒。

于 2012-08-02T18:03:32.037 回答
2

以防万一,如果您有很长的列列表,请使用 summarise_if()

如果数据类型为 int,则汇总所有列

library(dplyr)
shop %>% 
  group_by(shop_id, shop_name, city) %>% 
  summarise_if(is.integer, sum)
于 2019-02-07T13:37:41.537 回答