lse*_*ohn 3 r aggregation dataframe
我有一张桌子看起来像:
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
....
Run Code Online (Sandbox Code Playgroud)
我想转换表,以便将store_id放入多列,而value是sale_num.该表应如下:
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
......
Run Code Online (Sandbox Code Playgroud)
当我使用小规模的cast函数,原始表中的1000行,没有问题.
但是,原始表在R中有38,000,000行和comsumes 1.5 GB内存.当我使用强制转换功能时,该函数花费大约34 GB内存,并且它无休止地运行.
有什么问题呢?还有其他方法吗?
我们可以使用dcast
from data.table
.它应该比cast
from 更高效reshape
.我们将'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
Run Code Online (Sandbox Code Playgroud)