如何使用 dplyr 将累积列添加到 R 数据帧? [英] How to add a cumulative column to an R dataframe using dplyr?

查看:33
本文介绍了如何使用 dplyr 将累积列添加到 R 数据帧?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我和这篇文章有同样的问题,但我想使用dplyr:

I have the same question as this post, but I want to use dplyr:

使用 R 数据框,例如:

With an R dataframe, eg:

df <- data.frame(id = rep(1:3, each = 5)
                 , hour = rep(1:5, 3)
                 , value = sample(1:15))

如何添加与 id 匹配的累积总和列?

how do I add a cumulative sum column that matches the id?

没有 dplyr 上一篇文章的公认解决方案是:

Without dplyr the accepted solution of the previous post is:

df$csum <- ave(df$value, df$id, FUN=cumsum)

推荐答案

喜欢这个吗?

df <- data.frame(id = rep(1:3, each = 5),
                 hour = rep(1:5, 3),
                 value = sample(1:15))

mutate(group_by(df,id), csum=cumsum(value))

或者如果你使用 dplyr 的管道操作符:

Or if you use the dplyr's piping operator:

df %>% group_by(id) %>% mutate(csum = cumsum(value))

两种情况下的结果:

Source: local data frame [15 x 4]
Groups: id

   id hour value csum
1   1    1     4      4
2   1    2    14     18
3   1    3     8     26
4   1    4     2     28
5   1    5     3     31
6   2    1    10     10
7   2    2     7     17
8   2    3     5     22
9   2    4    12     34
10  2    5     9     43
11  3    1     6      6
12  3    2    15     21
13  3    3     1     22
14  3    4    13     35
15  3    5    11     46

这篇关于如何使用 dplyr 将累积列添加到 R 数据帧?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆