在dplyr

时间:2015-12-07 12:46:57

标签: r dataframe aggregate dplyr group-summaries

我有兴趣找到一种有效的方式来获取汇总表格,其中包含:

  • 计算每组的唯一值
  • 所选变量的一组原始描述性统计数据

例如,在生成描述性统计数据的情况下,我使用以下代码:

data("mtcars")
require(dplyr)
mt_sum <- mtcars %>% 
  group_by(cyl) %>% 
  summarise_each(funs(min,max), hp, wt, disp)

将生成所需的输出:

> head(mt_sum)

Source: local data frame [3 x 7]

    cyl hp_min wt_min disp_min hp_max wt_max disp_max
  (dbl)  (dbl)  (dbl)    (dbl)  (dbl)  (dbl)    (dbl)
1     4     52  1.513     71.1    113  3.190    146.7
2     6    105  2.620    145.0    175  3.460    258.0
3     8    150  3.170    275.8    335  5.424    472.0

我有兴趣用数字来丰富数据,这个数字可以反映每个组的值计数。关于计数,这可以简单地完成:

mt_sum2 <- mtcars %>% 
  group_by(cyl) %>% 
  summarise(countObs = n())

将生成所需的数据:

> head(mt_sum2)
Source: local data frame [3 x 2]

    cyl countObs
  (dbl)    (int)
1     4       11
2     6        7
3     8       14 

问题

当我想同时应用两种转换时,会出现问题。

尝试1

例如代码:

mt_sum <- mtcars %>% 
  group_by(cyl) %>% 
  summarise_each(funs(min,max), hp, wt, disp) %>% 
  summarise(countObs = n())

将生成:

Source: local data frame [3 x 2]

    cyl countObs
  (dbl)    (int)
1     4       11
2     6        7
3     8       14

没有先前生成的描述性统计信息。

尝试2

代码:

mt_sum <- mtcars %>% 
  group_by(cyl) %>% 
  summarise_each(funs(min,max,n), hp, wt, disp)

预计会失败:

  

Error: n does not take arguments

尝试3(工作)

代码:

data("mtcars")
require(dplyr)
mt_sum <- mtcars %>% 
  group_by(cyl) %>% 
  summarise_each(funs(min,max), hp, wt, disp) %>% 
  left_join(y = data.frame(
    "Var1" = as.numeric(as.character(as.data.frame(table(mtcars$cyl))$Var1)),
    "Count" = as.character(as.data.frame(table(mtcars$cyl))$Freq)),
            by = c("cyl" = "Var1"))

将提供所需的数据:

> head(mt_sum)
Source: local data frame [3 x 8]

    cyl hp_min wt_min disp_min hp_max wt_max disp_max  Count
  (dbl)  (dbl)  (dbl)    (dbl)  (dbl)  (dbl)    (dbl) (fctr)
1     4     52  1.513     71.1    113  3.190    146.7     11
2     6    105  2.620    145.0    175  3.460    258.0      7
3     8    150  3.170    275.8    335  5.424    472.0     14

我认为这是制作此摘要的极其低效的方法。特别是,在使用大表时,动态创建对象 效率很低。我有兴趣以更有效的方式实现相同的结果,而不仅仅是为了合并而创建对象。特别是,我想在dplyr中做的事情对应于从表格的先前版本中获得额外的摘要。例如:

  1. 制作描述性统计数据
  2. 返回
  3. 后的数据
  4. 制作一些额外的统计数据并添加到最终数据

1 个答案:

答案 0 :(得分:3)

这是使用left_join

的另一个(更短)选项
mtcars %>% 
    group_by(cyl) %>%  
    summarise_each(funs(min,max), hp, wt, disp) %>% 
    left_join(count(mtcars, cyl))
#Joining by: "cyl"
#Source: local data frame [3 x 8]
#
#    cyl hp_min wt_min disp_min hp_max wt_max disp_max     n
#  (dbl)  (dbl)  (dbl)    (dbl)  (dbl)  (dbl)    (dbl) (int)
#1     4     52  1.513     71.1    113  3.190    146.7    11
#2     6    105  2.620    145.0    175  3.460    258.0     7
#3     8    150  3.170    275.8    335  5.424    472.0    14