【问题标题】:dplyr summary by group using cumulative approachdplyr 使用累积方法按组汇总
【发布时间】:2020-07-07 15:41:27
【问题描述】:

我有一个这样的data.frame

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

library(dplyr)

我想对每个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 

我做了一个传统的 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

我可以使用 dplyr 做到这一点吗?

【问题讨论】:

  • 有一个dplyr::cummean 函数用于累积平均值。如果您的数据按id 排序,那应该可以满足您的需求。
  • 谢谢。我试过你的建议。该函数没有给我我正在寻找的内容,它是一个摘要而不是一个运行平均值
  • 你想要的结果是什么?使用set.seed(),以便我们可以复制您的样本数据。并且可能会使其更小,以便您可以提供显示您想要的确切输出。我不确定“旗帜”与任何事情有什么关系。您似乎知道要为一个值做什么,所以我不确定您为什么要包括您已经知道该怎么做的部分。这似乎让事情变得更难理解了。
  • 好的。让我编辑问题

标签: r dplyr


【解决方案1】:
dat %>%
  group_by(id) %>%
  summarise(mean_x = mean(x), mean_y = mean(y)) %>%
  mutate(result = cumsum(mean_x) / cumsum(mean_y)) %>%
  pluck("result")

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-11
    • 2015-09-11
    • 1970-01-01
    • 2014-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多