简体   繁体   English

dplyr 使用累积方法按组汇总

[英]dplyr summary by group using cumulative approach

I have a data.frame like this我有一个这样的data.frame

dat <- data.frame(id = rep(1:4, each = 4),
                  x = 1:16,
                  y = 16:1)

library(dplyr)

I want to do following operation for each id我想为每个id做以下操作

for id 1, do mean(x)/mean(y), 
for id 2, do mean(x)/mean(y) where x and y includes values from id 1 and 2 
for id 3, do mean(x)/mean(y) where x and y includes values from id 1, 2 and 3 
for id 4, do mean(x)/mean(y) where x and y includes values from id 1, 2, 3 and 4 

I did a traditional for loop to do this我做了一个传统的 for 循环来做到这一点

temp.vec <- list()
for(l in sort(unique(dat$id))){
  
  temp.vec[[l]] <- dat %>% 
                   dplyr::filter(id <= l) %>%
                   dplyr::summarise(value = mean(x)/mean(y)) 
  print(l)
}

result <- rbindlist(temp.vec)
result 
value
1: 0.1724138
2: 0.3600000
3: 0.6190476
4: 1.0000000

Can I do this using dplyr?我可以使用 dplyr 执行此操作吗?

dat %>%
  group_by(id) %>%
  summarise(mean_x = mean(x), mean_y = mean(y)) %>%
  mutate(result = cumsum(mean_x) / cumsum(mean_y)) %>%
  pluck("result")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM