0

I would like to have a sequence along each Blocks as such:

Blocks  MySeq     
1      1        
1      2       
2      1        
2      2       
1      1        
1      2        
1      3        
1      4        
3      1        
3      2        
3      3        
4      1
4      2
4      3
4      4

Based on this I have try

myDf %>% dplyr::mutate(MySeq= seq(1:length(unique(Blocks)),rle(Blocks)$"lengths")

However, the sequence is not resetting with each new block. See below:

Blocks  MySeq     
    1      1        
    1      2       
    2      1        
    2      2       
    1      3        
    1      4        
    1      5        
    1      6        
    3      1        
    3      2        
    3      3        
    4      1
    4      2
    4      3
    4      4

How can I make a new sequence from each individual Blocks?

Community
  • 1
  • 1
Wistar
  • 3,770
  • 4
  • 45
  • 70

2 Answers2

2

Try this

unlist(sapply(rle(df1$Blocks)$lengths,seq_len))
user2100721
  • 3,557
  • 2
  • 20
  • 29
1

We can use rleid from data.table by grouping the rleid of 'Blocks' and assign (:=) 'MySeq' as the sequence of rows.

library(data.table)
setDT(df1)[, MySeq := seq_len(.N) , .(rleid(Blocks))]
df1
#    Blocks MySeq
# 1:      1     1
# 2:      1     2
# 3:      2     1
# 4:      2     2
# 5:      1     1
# 6:      1     2
# 7:      1     3
# 8:      1     4
# 9:      3     1
#10:      3     2
#11:      3     3
#12:      4     1
#13:      4     2
#14:      4     3
#15:      4     4

Or if we are using base R, then sequence of lengths will get the expected output

sequence(rle(df1$Blocks)$lengths)
#[1] 1 2 1 2 1 2 3 4 1 2 3 1 2 3 4

data

df1 <- structure(list(Blocks = c(1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 3L, 
3L, 3L, 4L, 4L, 4L, 4L)), .Names = "Blocks", row.names = c(NA, 
 -15L), class = "data.frame")
akrun
  • 874,273
  • 37
  • 540
  • 662