背景
有个 R 数据文件(.Rdata),里面存了一个名为 data 的数据框,包含 5万多个观测,2千多个变量,每个变量都有 label 等属性
> str(data) 'data.frame': 5w obs. of 2k variables: $ n_eid : num 1e+06 1e+06 1e+06 1e+06 1e+06 ... ..- attr(*, "label")= chr "Encoded anonymised participant ID" $ age0 : num 60 62 66 42 55 47 48 61 69 43 ... ..- attr(*, "label")= chr "age, years" ..- attr(*, "source_field")= chr "s_53_0_0, n_34_0_0" $ sex : Factor w/ 2 levels "0","1": 2 1 2 2 1 1 2 2 2 1 ... ..- attr(*, "labels")= Named chr [1:2] "Female" "Male" .. ..- attr(*, "names")= chr [1:2] "0" "1" ..- attr(*, "label")= chr "Sex" ..- attr(*, "source_field")= chr "n_31_0_0" $ height0 : num 181 158 191 177 172 165 172 177 171 158 ... ..- attr(*, "label")= chr "Standing height, cm" ..- attr(*, "source_field")= chr "n_50_0_0" $ weight0 : num 90.1 89.1 96.1 73.7 87.4 ... ..- attr(*, "label")= chr "Weight, Kg" ..- attr(*, "source_field")= chr "n_21002_0_0" $ bmi0 : num 27.5 35.7 26.3 23.5 29.5 ... ..- attr(*, "label")= chr "Body mass index (BMI), Kg/m2" ..- attr(*, "source_field")= chr "n_21001_0_0"
原始文件大小约为 300M
> file.size('~/1_前处理.Rdata')/ 1024^2 [1] 298.9328
当在 R studio 加载再保存后,文件大小变为了 7.3G !!!
> load('~/1_前处理.Rdata') > save(all, file = '~/1_前处理copy.Rdata') > > file.size('~/1_前处理copy.Rdata')/ 1024^3 [1] 7.403472
测试
经过多次测试发现,在 R 软件种,或 terminal 中打开 R,或用 Rscript 调用脚本,运行以下代码
> file.size('~/1_前处理.Rdata')/1024^2 > save(all, file = '~/1_前处理copy.Rdata') > file.size('~/1_前处理copy.Rdata')/ 1024^3
产生的 copy.Rdata 文件大小均没有膨胀(298.93 M)
推测原因
在 R 内存中数据对象一直是被压缩/引用共享的状态。如数据中有大量重复的数据结构,该数据会被完美压缩。Rstudio 中为了可视化,大部分 R 对象均被展开,非常消耗内存,当 save 该对象时,这个对象不会被真正压缩,所以文件会非常大。