如何在 R 中查找累积和,如果值为 1 则重新开始它?
有时,我们希望找到条件累积和,这些条件可以在出现特定值时重置累积和。例如,找到变量帧的累积和,但在出现 1 时重新开始求和。在 R 中,我们可以借助 with、ave 和 cumusum 函数,如下面的示例所示,来实现此目的。
示例 1
考虑以下数据帧
> ID<-1:20 > Ratings<-sample(0:2,20,replace=TRUE) > df1<-data.frame(ID,Ratings) > df1
输出
ID Ratings 1 1 0 2 2 2 3 3 0 4 4 0 5 5 0 6 6 2 7 7 1 8 8 0 9 9 1 10 10 2 11 11 2 12 12 1 13 13 1 14 14 0 15 15 0 16 16 2 17 17 0 18 18 0 19 19 1 20 20 0
找到累积和并在出现 1 时重新开始
示例
> df1<-with(df1,ave(Ratings,cumsum(Ratings==1),FUN=cumsum)) > df1
输出
[1] 0 2 2 2 2 4 1 1 1 3 5 1 1 1 1 3 3 3 1 1
示例 2
> x<-1:20 > y<-sample(1:4,20,replace=TRUE) > df2<-data.frame(x,y) > df2
输出
x y 1 1 2 2 2 2 3 3 1 4 4 1 5 5 3 6 6 2 7 7 2 8 8 3 9 9 1 10 10 4 11 11 2 12 12 1 13 13 1 14 14 3 15 15 2 16 16 2 17 17 1 18 18 4 19 19 4 20 20 4
找到累积和并在出现 1 时重新开始
示例
> df2<-with(df2,ave(y,cumsum(y==1),FUN=cumsum)) > df2
输出
[1] 2 4 1 1 4 6 8 11 1 5 7 1 1 4 6 8 1 5 9 13
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP