Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a sequence column for repeated values?

Tags:

r

I have a df that is created like so:

ID <- c(1, 2, 3, 4)
count <- c(2, 4, 6, 10)
data <- data.frame(ID, count)
data <- data[rep(1:nrow(data), data$count),]
print(data)

I want to have another column that essentially prints the sequence of the count? I'm not sure how best to describe what I'm getting at basically I want it to look like the following output:

    ID count sequence
1    1     2        1
1.1  1     2        2
2    2     4        1
2.1  2     4        2
2.2  2     4        3
2.3  2     4        4
3    3     6        1
3.1  3     6        2
3.2  3     6        3
3.3  3     6        4
3.4  3     6        5
3.5  3     6        6
4    4    10        1
4.1  4    10        2
4.2  4    10        3
4.3  4    10        4
4.4  4    10        5
4.5  4    10        6
4.6  4    10        7
4.7  4    10        8
4.8  4    10        9
4.9  4    10       10

Thanks

like image 437
Miki Parr Avatar asked Dec 09 '25 21:12

Miki Parr


1 Answers

data$sequence <- unlist(lapply( with(data, rle(count)$lengths), seq_len))
data
   ID count sequence
1    1     2        1
1.1  1     2        2
2    2     4        1
2.1  2     4        2
2.2  2     4        3
2.3  2     4        4
3    3     6        1
3.1  3     6        2
3.2  3     6        3
3.3  3     6        4
3.4  3     6        5
3.5  3     6        6
4    4    10        1
4.1  4    10        2
4.2  4    10        3
4.3  4    10        4
4.4  4    10        5
4.5  4    10        6
4.6  4    10        7
4.7  4    10        8
4.8  4    10        9
4.9  4    10       10
like image 153
Sathish Avatar answered Dec 12 '25 15:12

Sathish



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!