cast 函数非常耗内存,如何处理?
cast function is extremely memory consuming, how to handle it?
我有一个 table 看起来像:
date item_id store_id sale_num
1/1/15 33 1 10
1/1/15 33 2 12
1/1/15 33 3 15
1/1/15 44 1 54
1/1/15 44 3 66
1/2/15 33 1 14
....
我想转换table,以便将store_id放入多个列中,值是sale_num。 table 应该是这样的:
date item_id store1 store2 store3
1/1/15 33 10 12 15
1/1/15 44 54 NA 66
1/2/15 33 14 NA NA
......
当我在小范围内使用 cast 函数执行此操作时,原始 table 中有 1000 行,没有问题。
然而,原始 table 有 38,000,000 行,在 R 中占用 1.5 GB 内存。
当我使用 cast 函数时,该函数占用大约 34 GB 内存,并且它会无限运行。
这是什么问题呢?还有其他方法吗?
我们可以使用 data.table
中的 dcast
。它应该比 reshape
中的 cast
更有效。我们将 'data.frame' 转换为 'data.table' (setDT(df1)
),然后使用 dcast
.
library(data.table)
dcast(setDT(df1), date+item_id~ paste0("store",
store_id), value.var="sale_num")
# date item_id store1 store2 store3
#1: 1/1/15 33 10 12 15
#2: 1/1/15 44 54 NA 66
#3: 1/2/15 33 14 NA NA
我有一个 table 看起来像:
date item_id store_id sale_num
1/1/15 33 1 10
1/1/15 33 2 12
1/1/15 33 3 15
1/1/15 44 1 54
1/1/15 44 3 66
1/2/15 33 1 14
....
我想转换table,以便将store_id放入多个列中,值是sale_num。 table 应该是这样的:
date item_id store1 store2 store3
1/1/15 33 10 12 15
1/1/15 44 54 NA 66
1/2/15 33 14 NA NA
......
当我在小范围内使用 cast 函数执行此操作时,原始 table 中有 1000 行,没有问题。
然而,原始 table 有 38,000,000 行,在 R 中占用 1.5 GB 内存。 当我使用 cast 函数时,该函数占用大约 34 GB 内存,并且它会无限运行。
这是什么问题呢?还有其他方法吗?
我们可以使用 data.table
中的 dcast
。它应该比 reshape
中的 cast
更有效。我们将 'data.frame' 转换为 'data.table' (setDT(df1)
),然后使用 dcast
.
library(data.table)
dcast(setDT(df1), date+item_id~ paste0("store",
store_id), value.var="sale_num")
# date item_id store1 store2 store3
#1: 1/1/15 33 10 12 15
#2: 1/1/15 44 54 NA 66
#3: 1/2/15 33 14 NA NA