什么是数据表中的dplyr mutate和summary?

时间:2016-07-07 01:52:07

标签: r data.table dplyr

在包dplyr中,我们有操作:

mtcars %>%
    group_by(cyl) %>%
    summarise(max_mpg = max(mpg)) # output one result for each unique group,
                                  # result has nGroups number of rows.

    cyl max_mpg
  <dbl>   <dbl>
1     4    33.9
2     6    21.4
3     8    19.2

mtcars %>%
    group_by(cyl) %>%
    mutate(max_mpg = max(mpg)) # output the same result for every row in the                       
                               # same group, result has same number of rows
                               # as input

Source: local data frame [32 x 12]
Groups: cyl [3]

     mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb max_mpg
   (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl) (dbl)   (dbl)
1   21.0     6 160.0   110  3.90 2.620 16.46     0     1     4     4    21.4
2   21.0     6 160.0   110  3.90 2.875 17.02     0     1     4     4    21.4
3   22.8     4 108.0    93  3.85 2.320 18.61     1     1     4     1    33.9
4   21.4     6 258.0   110  3.08 3.215 19.44     1     0     3     1    21.4
5   18.7     8 360.0   175  3.15 3.440 17.02     0     0     3     2    19.2
6   18.1     6 225.0   105  2.76 3.460 20.22     1     0     3     1    21.4
7   14.3     8 360.0   245  3.21 3.570 15.84     0     0     3     4    19.2
8   24.4     4 146.7    62  3.69 3.190 20.00     1     0     4     2    33.9
9   22.8     4 140.8    95  3.92 3.150 22.90     1     0     4     2    33.9
10  19.2     6 167.6   123  3.92 3.440 18.30     1     0     4     4    21.4
...

data.table中的这些操作的等效内容是什么?

我认为mutate

提供
data.table(mtcars) %>% 
    .[, max := max(mpg), by = cyl]

但我不知道如何得到summarise的等价物。我可以添加,无论出于何种原因,如果你没有:=它会summarise,例如:

data.table(mtcars) %>% .[, max(mpg), by = cyl]

给出

   cyl   V1
1:   6 21.4
2:   4 33.9
3:   8 19.2

但是如何为创建的V1列指定名称并不明显。

1 个答案:

答案 0 :(得分:6)

library(data.table)
MT <- data.table(mtcars)

# summarise
MT[, .(max_mpg = max(mpg)), by = cyl]

   cyl max_mpg
1:   6    21.4
2:   4    33.9
3:   8    19.2

# mutate
MT[, max_mpg := max(mpg), by = cyl]

max_mpg已添加到MT,但此命令不会显示数据

显示数据:

MT[, max_mpg := max(mpg), by = cyl][]

由于数据有32行,只显示头部:

MT[, max_mpg := max(mpg), by = cyl][,head(.SD, 6)]

     mpg cyl disp  hp drat    wt  qsec vs am gear carb max_mpg
 1: 21.0   6  160 110 3.90 2.620 16.46  0  1    4    4    21.4
 2: 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4    21.4
 3: 22.8   4  108  93 3.85 2.320 18.61  1  1    4    1    33.9
 4: 21.4   6  258 110 3.08 3.215 19.44  1  0    3    1    21.4
 5: 18.7   8  360 175 3.15 3.440 17.02  0  0    3    2    19.2
 6: 18.1   6  225 105 2.76 3.460 20.22  1  0    3    1    21.4

如果您希望按cyl排序:(由@thelatemail建议的代码)

MT[, .(max_mpg = max(mpg)), keyby=cyl]

   cyl max_mpg
1:   4    33.9
2:   6    21.4
3:   8    19.2

修改

添加此内容以回应@Alex的评论

data("mtcars")
setDT(mtcars)[, .(max_mpg = max(mpg)), by = cyl]