group , cycle by rule

Published by onesixx on

set.seed(100)
sData <- data.table(
        stepNm = c("Q","W","E") %>% rep(5),
        numVal = runif(15) %>% round(1) *10
      )
sData[, gID:=seq_len(.N), by=stepNm]

sData[, gID:=rowid(stepNm)]

sData[, gID:=ave(numVal, stepNm, FUN=seq_along)]

sData %>% group_by(stepNm) %>% mutate(gID=row_number()) 
    stepNm numVal
 1:      Q      6
 2:      W      9
 3:      E      8
 4:      Q      8
 5:      W      1
 6:      E      5
 7:      Q      6
 8:      W      9
 9:      E     10
10:      Q      0
11:      W      6
12:      E      7
13:      Q      2
14:      W      3
15:      E      7
    stepNm numVal gID
 1:      Q      7   1
 2:      W     10   1
 3:      E      7   1
 4:      Q      0   2
 5:      W      5   2
 6:      E      8   2
 7:      Q      8   3
 8:      W      1   3
 9:      E      2   3
10:      Q     10   4
11:      W      0   4
12:      E      9   4
13:      Q      7   5
14:      W      2   5
15:      E      8   5
#sData[, gID:=seq_len(.N), by=stepNm]

sData[, gID:=seq(from=6,length.out=.N), by=stepNm]
#     stepNm numVal gID
#  1:      Q      7   6
#  2:      W     10   6
#  3:      E      7   6
#  4:      Q      0   7
#  5:      W      5   7
#  6:      E      8   7
#  7:      Q      8   8
#  8:      W      1   8
#  9:      E      2   8
# 10:      Q     10   9
# 11:      W      0   9
# 12:      E      9   9
# 13:      Q      7  10
# 14:      W      2  10
# 15:      E      8  10
Categories: R Reshaping

onesixx

Blog Owner

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x