我可以帮助您将维度为1558810 x 84的长数据转换成1558810 x 4784的宽数据。以下是详细说明。
我的原始数据如下 -
数据有三个主要列 -
id empId dept
1 a social
2 a Hist
3 a math
4 b comp
5 a social
6 b comp
7 c math
8 c Hist
9 b math
10 a comp
id是唯一的关键字,它告诉我们某个员工在某天去了哪个大学部门。我需要按照以下方式对其进行转换。
id empId dept social Hist math comp
1 a social 1 0 0 0
2 a Hist 0 1 0 0
3 a math 0 0 1 0
4 b comp 0 0 0 1
5 a social 1 0 0 0
6 b comp 0 0 0 1
7 c math 0 0 1 0
8 c Hist 0 1 0 0
9 b math 0 0 1 0
10 a comp 0 0 0 1
我有两个数据集,一个包含4.9万行,另一个包含155万行。对于较小的数据集,其中有1100个唯一的部门值,我使用了reshape2包中的dcast函数来获取所需的数据集(因此,转换后的数据将具有3+1100列和49k行)。但是当我在具有4700个唯一部门值的大型数据集上使用同样的函数时,我的R会因为内存问题而崩溃。我尝试了各种其他替代方法,如xtabs、reshape等,但每次都因为内存错误而失败。
现在,我已经采用了一个粗糙的FOR循环来实现这个目的-
columns <- unique(ds$dept)
for(i in 1:length(unique(ds$dept)))
{
ds[,columns[i]] <- ifelse(ds$dept==columns[i],1,0)
}
但是这种方法非常缓慢,代码已经运行了10个小时了。我是否遗漏了什么解决方法?
任何建议都将非常有帮助!
dcast.data.table
应该更快。然而,我没有进行基准测试。 - akruntidyr
的spread
函数应该能够很好地处理大数据。 - bdecaf