简体   繁体   中英

dplyr summary by group using cumulative approach

I have a data.frame like this

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

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

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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