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屋!
查看全文