嵌套与未通过(整洁)data.frame的大小?

时间:2015-05-12 00:08:42

标签: r performance memory pryr

This question使用包含list-columns(嵌套)的data.frame。它让我想知道为什么/如果以这种方式工作有优势。我假设你想要最小化每个表使用的内存量......但是当我检查时我很惊讶:

比较嵌套格式与整齐格式的表格大小:

1。生成2-col和5-col data.frame:

的嵌套/整理版本
    library(pryr)
    library(dplyr)
    library(tidyr)
    library(ggvis)
    n <- 1:1E6
    df <- data_frame(id = n, vars = lapply(n, function(x)  x <- sample(letters,sample(1:26,1))))
    dfu <- df %>% unnest(vars)
    df_morecols <- data_frame(id = n, other1 = n, other2 = n, other3 = n,
                     vars = lapply(n, function(x)  x <- sample(letters,sample(1:26,1))))
    dfu_morecols <- df_morecols %>% unnest(vars)
他们看起来像是:

    head(df)
    #> Source: local data frame [6 x 2]

    #>   id      vars
    #> 1  1 <chr[16]>
    #> 2  2  <chr[4]>
    #> 3  3 <chr[26]>
    #> 4  4  <chr[9]>
    #> 5  5 <chr[11]>
    #> 6  6 <chr[18]>

    head(dfu)
    #> Source: local data frame [6 x 2]

    #>   id vars
    #> 1  1    k
    #> 2  1    d
    #> 3  1    s
    #> 4  1    j
    #> 5  1    m
    #> 6  1    t

    head(df_morecols)
    #> Source: local data frame [6 x 5]

    #>   id other1 other2 other3      vars
    #> 1  1      1      1      1  <chr[4]>
    #> 2  2      2      2      2 <chr[22]>
    #> 3  3      3      3      3 <chr[24]>
    #> 4  4      4      4      4  <chr[6]>
    #> 5  5      5      5      5 <chr[15]>
    #> 6  6      6      6      6 <chr[11]>

    head(dfu_morecols)
    #> Source: local data frame [6 x 5]

    #>   id other1 other2 other3 vars
    #> 1  1      1      1      1    r
    #> 2  1      1      1      1    p
    #> 3  1      1      1      1    s
    #> 4  1      1      1      1    w
    #> 5  2      2      2      2    l
    #> 6  2      2      2      2    j

2。计算对象大小和col大小

from: lapply(list(df,dfu,df_morecols,dfu_morecols),object_size)

  

170 MB与162 MB对于嵌套与整洁的2-col df
    对于嵌套与整齐的5-col df

,为170 MB与324 MB
    col_sizes <- sapply(c(df,dfu,df_morecols,dfu_morecols),object_size)
    col_names <- names(col_sizes)
    parent_obj <- c(rep(c('df','dfu'),each = 2),
                    rep(c('df_morecols','dfu_morecols'),each = 5))
    res <- data_frame(parent_obj,col_names,col_sizes) %>% 
      unite(elementof, parent_obj,col_names, remove = F)

3。绘制由父对象着色的列大小:

    res %>% 
      ggvis(y = ~elementof, x = ~0, x2 = ~col_sizes, fill = ~parent_obj) %>% 
      layer_rects(height = band())

plot of sizes

的问题:

  • 与嵌套的2-col df相比,整洁的2-col df的占地面积更小?
  • 为什么这种效果不会改变为5-col df?

0 个答案:

没有答案