Sean
Sean

Reputation: 119

How to create a new variable that resets based on a condition in R

I have the following dataframe in r:

block time xp yp ps cr.info ts
1 1 2150472 1021. 565. 3485 ... 0
2 1 2150473 1021. 565. 3481 ... 0.001
3 1 2150474 1021. 565. 3477 ... 0.002
4 1 2150475 1021. 564 3478 ... 0.003

The variable "ts" increases in milliseconds for entire dataset, I would like to create a new variable which also increases in milliseconds but which starts from zero each time the conditional variable "block" changes value, so that each block has its own separate timer, as demonstrated in the table below.

block time xp yp ps cr.info ts block_ts
1 1 2150472 1021. 565. 3485 ... 0 0
2 1 2150473 1021. 565. 3481 ... 0.001 0.001
3 1 2150474 1021. 565. 3477 ... 0.002 0.002
4 1 2150475 1021. 564 3478 ... 0.003 0.003
5 2 2150476 1040. 578. 5678 ... 0.004 0
6 2 2150477 1041. 579. 5688 ... 0.005 0.001

Thanks in advance,

Sean

Upvotes: 2

Views: 51

Answers (1)

akrun
akrun

Reputation: 887223

We can use a group by operation. After grouping by 'block', create the sequence from 0, specify the length.out as the number of rows for each block (n()) and the by as the increment in each step

library(dplyr)
df1 %>%
    group_by(block) %>%
    mutate(block_ts = seq(0, length.out = n(), by = 0.001))

Upvotes: 4

Related Questions