I have a data set like this,
dat <- data.frame(d1=c(0,1,0,1,0),
d2=c(0,1,1,1,0),d3=c(1,0,1,1,0),
d4=c(1,0,0,0,0),d5=c(1,1,1,0,0))
dat
d1 d2 d3 d4 d5
1 0 0 1 1 1
2 1 1 0 0 1
3 0 1 1 0 1
4 1 1 1 0 0
5 0 0 0 0 0
If I consider each row is set of run for an individual. I want to calculate an indicator variable named "indicator" based on run. For example, individual 1 run is (0,0,1,1,1) for this backward length of run with value first 1's is 3. On the other hand, for individual 3 run is (0,1,1,0,1), backward length of run with value first 1,s is 1. Required data set is like this.
d1 d2 d3 d4 d5 indicator
0 0 1 1 1 3
1 1 0 0 1 1
0 1 1 0 1 1
1 1 1 0 0 3
0 0 0 0 0 0
I have tried in this way,
indicator <- NULL
for(i in 1:5){
indicator[i] <- rev(sequence(rle(dat[i,])$lengths))[1]
}
indicator[1:5]
cbind(dat, indicator=indicator[1:5])
But this gives data like this,
d1 d2 d3 d4 d5 indicator
1 0 0 1 1 1 3
2 1 1 0 0 1 1
3 0 1 1 0 1 1
4 1 1 1 0 0 2
5 0 0 0 0 0 5
Could any body help me to solve this?