dplyr group_by和cummean函数

时间:2014-04-19 18:47:06

标签: r dplyr

我希望下面的代码输出一个包含三行的数据框,每行代表计算每组cyl的平均值后的mpg累积平均值:

library(dplyr)
mtcars %>%
arrange(cyl) %>%
group_by(cyl) %>%
summarise(running.mean.mpg = cummean(mpg))

这是我预期会发生的事情:

mean_cyl_4 <- mtcars %>% 
filter(cyl == 4) %>%
summarise(mean(mpg))

mean_cyl_4_6 <- mtcars %>% 
filter(cyl == 4 | cyl == 6) %>%
summarise(mean(mpg))

mean_cyl_4_6_8 <- mtcars %>% 
filter(cyl == 4 | cyl == 6 | cyl == 8) %>%
summarise(mean(mpg))

data.frame(cyl = c(4,6,8), running.mean.mpg = c(mean_cyl_4[1,1], mean_cyl_4_6[1,1], mean_cyl_4_6_8[1,1]))

  cyl running.mean.mpg
1   4     26.66364
2   6     23.97222
3   8     20.09062

dplyr如何忽略group_by(cyl)

3 个答案:

答案 0 :(得分:5)

require("dplyr")

mtcars %>%
  arrange(cyl) %>%
  group_by(cyl) %>%
  mutate(running.mean.mpg = cummean(mpg)) %>%
  select(cyl, running.mean.mpg)

# Source: local data frame [32 x 2]
# Groups: cyl
# 
# # cyl running.mean.mpg
# # 1    4         22.80000
# # 2    4         23.60000
# # 3    4         23.33333
# # 4    4         25.60000
# # 5    4         26.56000
# # 6    4         27.78333
# # 7    4         26.88571
# # 8    4         26.93750

为了实验,这也适用于data.table。 我的意思是,您还必须加载dplyr以使cummean()可用。

require("data.table")
DT <- as.data.table(mtcars)
DT[,j=list(
  running.mean.mpg = cummean(mpg)
  ), by="cyl"]

答案 1 :(得分:0)

使用mutate而不是summarise

答案 2 :(得分:0)

这可以随意使用。

mtcars %>%
arrange(cyl) %>%
mutate(running.mean.mpg = cummean(mpg)) %>%
select(cyl, running.mean.mpg)%>%
group_by(cyl)%>%
summarize(target=last(running.mean.mpg))