assign number every time an event occurs in r -
i have data:
t <- c(na,na,na,1,na,na,na,na,1,na,1) dt <- data.table(t) t 1: na 2: na 3: na 4: 1 5: na 6: na 7: na 8: na 9: 1 10: na 11: 1
is possible create new column z , assign number in ascending order every time 1 occurs in t column, this:
t z 1: na na 2: na na 3: na na 4: 1 1 5: na na 6: na na 7: na na 8: na na 9: 1 2 10: na na 11: 1 3
thank you
we can create logical index of non-na elements in 'i' , assign ('z') sequence of 't'
dt[!is.na(t), z := seq_along(t)] dt # t z # 1: na na # 2: na na # 3: na na # 4: 1 1 # 5: na na # 6: na na # 7: na na # 8: na na # 9: 1 2 #10: na na #11: 1 3
Comments
Post a Comment