R - 条件递增 [英] R - conditional incrementation
本文介绍了R - 条件递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这对代码来说应该是微不足道的,但在 R 中想不出优雅的单行代码.我有一个如下的数据框:
This should be trivial to code but could not think of an elegant one-liner in R. I have a dataframe as below:
data <- data.frame( index= seq(1:20), event=rep(0,20) )
data$event[10] <- 1
data$event[15] <- 1
我只想添加 start
和 stop
计数器列,它们以 10 为单位递增并在观察到 event=1
后立即重置.因此,带有这两个附加列的所需输出将是:
I simply want to add start
and stop
counter columns that increment in 10's and reset right after an event=1
is observed. So the desired output with these two additional columns would be:
index event start stop
1 1 0 0 10
2 2 0 10 20
3 3 0 20 30
4 4 0 30 40
5 5 0 40 50
6 6 0 50 60
7 7 0 60 70
8 8 0 70 80
9 9 0 80 90
10 10 1 90 100
11 11 0 0 10
12 12 0 10 20
13 13 0 20 30
14 14 0 30 40
15 15 1 40 50
16 16 0 0 10
17 17 0 10 20
18 18 0 20 30
19 19 0 30 40
20 20 0 40 50
显然,data$stop <- data$start + 10
但是我怎样才能apply()
描述的 start
增量 loigc?
Obviously, data$stop <- data$start + 10
but how can I apply()
the start
incrementation loigc as described?
推荐答案
这个怎么样:
Reduce(function(x,y) (1-y)*(x+10), data$event[-nrow(data)], accumulate=T, init=0)
这篇关于R - 条件递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文