r - R- Include starting point in cumsum function
问题描述
I have this data.frame
:
a b
[1,] 1 0
[2,] 2 0
[3,] 3 0
[4,] 4 0
[5,] 5 0
[6,] 6 1
[7,] 7 2
[8,] 8 3
[9,] 9 4
[10,] 10 5
I want to apply cumsum
on column a
only when its corresponding value on column b
is different from 0.
I tried this below but it doesn't include a starting condition on the cumsum:
df_cumsum <- cbind(c(1:10), c(0,0,0,0,0,1,2,3,4,5),
as.data.frame(ave(A[,1], A[,2] != 0, FUN=cumsum)))
Unfortunately, I obtain a cumsum
over the whole column:
a b c
1 1 0 1
2 2 0 3
3 3 0 6
4 4 0 10
5 5 0 15
6 6 1 6
7 7 2 13
8 8 3 21
9 9 4 30
10 10 5 40
I would like to obtain:
a b c
1 1 0 0
2 2 0 0
3 3 0 0
4 4 0 0
5 5 0 0
6 6 1 6
7 7 2 13
8 8 3 21
9 9 4 30
10 10 5 40
Thanks for help!
解决方案
假设输入df
在最后的注释中可重现,试试这个。它将任何a
值为b
0 的值清零。
transform(df, cum = cumsum((b > 0) * a))
给予:
a b cum
1 1 0 0
2 2 0 0
3 3 0 0
4 4 0 0
5 5 0 0
6 6 1 6
7 7 2 13
8 8 3 21
9 9 4 30
10 10 5 40
笔记
我们假设此输入以可重现的形式显示:
Lines <- "
a b
1 0
2 0
3 0
4 0
5 0
6 1
7 2
8 3
9 4
10 5"
df <- read.table(text = Lines, header = TRUE)
更新
a
并且b
被逆转了。修好了。
推荐阅读
- lisp - 制作适用于列表的球拍功能
- php - WordPress 查询以获取 ACF 字段的正确计数?
- sql - SQL中的窗口是什么?
- jwt - 当令牌的签名无效时,Passport 的 JWT 策略会发生什么?
- android - Android Recycleview 多个 ViewTypes 在 kotlin 中不起作用
- java - [错误]:无法在文件夹 'plugins' 中加载 'plugins\test.jar'
- c - 在 C 中创建 WinRT 对象的正确方法
- google-sheets - 合并多个公式以消除帮助列
- django - Django登录与休息框架
- video-compression - 如何在 VTM 上的源代码中定位并获取中间结果?