How to measure y length?

Im new to R and running into some problems determining the length of y to y = 1. Given sample:

         id<-c(1, 1, 1, 1, 1, 1, 1, 2, 2,2,2,2,2,2) 
         y<-c(0, 0, 0, 0, 1, 0, 1, 1, 0,0,0,0,0,1) 
         time<-c(1, 2, 3,4, 5, 6, 7, 1, 2,3,4,5,6,7)

      

Data <-data.frame (id, y, time)

        id  y   time    desired lenght
         1  0   1            1
         1  0   2            2
         1  0   3            3
         1  0   4            4
         1  1   5            1
         1  0   6            2
         1  1   7            1
         2  1   1            1
         2  0   2            1
         2  0   3            2
         2  0   4            3
         2  0   5            4
         2  0   6            5
         2  1   7            1

      

+3


source to share


1 answer


It seems a little odd that the length in y=1

should be 1 and not 0, but if that's what you want, you can do it with



data$desired <- unlist(with(rle(data$y), 
    Map(function(l,v) 
        if(v==1) rep(1, l) else seq.int(l),
    lengths, values))
)
data

#    id y time desired
# 1   1 1    1       1
# 2   1 0    2       1
# 3   1 0    3       2
# 4   1 0    4       3
# 5   1 1    5       1
# 6   1 0    6       1
# 7   1 1    7       1
# 8   2 1    1       1
# 9   2 0    2       1
# 10  2 0    3       2
# 11  2 0    4       3
# 12  2 0    5       4
# 13  2 0    6       5
# 14  2 1    7       1

      

+3


source







All Articles