id random count 0 -1 1 1 1 2 0 -1 0 -2 1 1 0 -1 1 1 0 -1 b 0 -1 b 0 -2 b 1 1 b 0 -1 b 1 1 b 0 -1 b 0 -2 b 0 -3
id
player , random
binary 0
or 1
, want create count column counts sequences of 1's , 0's player , preferably without loops since database big.
here's dplyr
solution
dat %>% transform(idx = c(0,cumsum(random[-1l] != random[-length(random)]))) %>% group_by(id, idx) %>% mutate(count = -1*cumsum(random == 0) + cumsum(random == 1)) %>% ungroup() %>% select(-idx) source: local data frame [17 x 3] id random count 1 0 -1 2 1 1 3 1 2 4 0 -1 5 0 -2 6 1 1 7 0 -1 8 1 1 9 0 -1 10 b 0 -1 11 b 0 -2 12 b 1 1 13 b 0 -1 14 b 1 1 15 b 0 -1 16 b 0 -2 17 b 0 -3
Comments
Post a Comment